Java 如何使用spring框架检查启动和停止?
嗨,我需要在我的应用程序启动时发送电子邮件,在我的应用程序停止时发送电子邮件 使用springJava 如何使用spring框架检查启动和停止?,java,spring,Java,Spring,嗨,我需要在我的应用程序启动时发送电子邮件,在我的应用程序停止时发送电子邮件 使用spring public class Main { public static void main(String[] args) { FileSystemXmlApplicationContext fac = new FileSystemXmlApplicationContext("config/applicationContext.xml"); } } 其余部分通过应用程序上下
public class Main {
public static void main(String[] args) {
FileSystemXmlApplicationContext fac = new FileSystemXmlApplicationContext("config/applicationContext.xml");
}
}
其余部分通过应用程序上下文连接起来
我想我可以只注入一个实现智能生命周期的简单bean,然后从
start()
和stop()
方法中发送一封电子邮件?Spring会在这些情况下自动引发事件
您可以通过创建ApplicationListener
bean来侦听事件:
@Component
public class ContextRefreshListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(final ContextRefreshedEvent event) {
// is called whenever the application context is initialized or refreshed
}
}
@组件
公共类ContextRefreshListener实现ApplicationListener{
@凌驾
ApplicationEvent上的公共无效(最终上下文刷新事件){
//每当初始化或刷新应用程序上下文时调用
}
}
Spring引发以下应用程序上下文事件:
- (ApplicationContext关闭)
- (ApplicationContext被初始化或刷新)
- (ApplicationContext被停止)
- (ApplicationContext被停止)
请参见您可以在默认的singleton作用域中使用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"/>
当然,您也可以使用spring来设置bean的属性…好的,我试着让您知道。谢谢我需要打个明确的电话吗?新的ClassPathXmlApplicationContext(“applicationContext.xml”);cac.start();似乎我需要显式调用start()和stop()。只有刷新事件是自动发布的。两个答案都一样好,但在我的情况下,我选择了这种方法并将其标记为已接受的答案。:)同样值得一提的是,要使其正常工作,您还需要registerShutdownHook()。@user432024:是否在容器未正确关闭其servlet上下文的情况下关闭JVM,情况真的很糟糕,您不确定是否能够执行任何操作:-(我知道,不能保证关机会完成或者不会被中断,但是如果没有registerShutDownhook(),bean的stop方法在我注册关机钩子之前从未被调用过。
@Configuration
public class Configurer {
@Bean(initMethod="onStart", destroyMethod="onStop")
StartAndStop startAndStop() {
return new StartAndStop();
}
... other beans configuration ...
}