gpt4 book ai didi

java - 如何使用 spring 框架检查启动和停止?

转载 作者:行者123 更新时间:2023-11-29 07:45:37 26 4
gpt4 key购买 nike

您好,我需要在我的应用程序启动时发送电子邮件,并在我的应用程序停止时发送电子邮件。

使用 Spring ...

public class Main {
public static void main(String[] args) {
FileSystemXmlApplicationContext fac = new FileSystemXmlApplicationContext("config/applicationContext.xml");
}
}

其余部分通过应用程序上下文连接...

我想我可以只注入(inject)一个实现智能生命周期的简单 bean,并从 start()stop() 方法中发送电子邮件?

最佳答案

您可以简单地在默认单例范围内使用一个 bean,并声明它的 init 和 destroy 方法。这个 bean 不需要遵守 Spring,可以是这样的:

public class StartAndStop {

public void onStart() {
// send the mail signaling start of application
...
}

public void onStop() {
// send the mail signaling stop of application
...
}
}

在 xml 配置中:

<bean class="org.example.StartAndStop" init-method="onStart" destroy-method="onStop"/>

并使用 Java 配置

@Configuration
public class Configurer {

@Bean(initMethod="onStart", destroyMethod="onStop")
StartAndStop startAndStop() {
return new StartAndStop();
}
... other beans configuration ...
}

当然也可以使用spring在bean上设置属性...

关于java - 如何使用 spring 框架检查启动和停止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26149643/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com