我目前正在尝试将Spring Boot应用程序部署到外部Tomcat实例中,并且遇到了一些关于如何最好地管理某些事物的实例化的问题。
按照目前的结构,我有一些类似的东西
public class MyClass extends SpringBootServletInitializer{
@Bean
public ThreadPool pool(){
return new ThreadPool();
}
@Bean
public BackgroundThread setupInbox() {
BackgroundThread inbox = new BackgroundThread(pool());
inbox.start();
return inbox;
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MyClass.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(MyClass.class, args);
}
}
其中BackgroundThread是监听AMQP型消息队列以获得新作业的线程。我知道Spring提供了一些RabbitMQ方法来做到这一点,但我们没有使用Rabbit来做这件事,所以它没有帮助。
正在部署的这个*.war文件的整个目的是通过消息传递向网络公开一些功能,所以我的问题是,在Spring的整个生命周期中实例化、启动和销毁BackgroundThread的最佳方式是什么?XML配置?
发布于 2016-09-07 20:36:35
From the docs:
JSR-250、@PostConstruct和@PreDestroy注释通常被认为是在现代
应用程序中接收生命周期回调的最佳实践。使用这些注释意味着您的bean不会耦合到Spring特定的接口。
For details see Section 7.9.8, “@PostConstruct and @PreDestroy”
这些注释是要放在一些初始化和清理方法上的:
@PostConstruct
public void initAfterStartup() {
...
}
@PreDestroy
public void cleanupBeforeExit() {
...
}
同样有用的还有:
每个SpringApplication都会向JVM注册一个关闭钩子,以确保ApplicationContext在退出时正常关闭。所有标准的Spring生命周期回调(比如DisposableBean接口,或者@PreDestroy注解)都可以使用。
此外,如果beans希望在应用程序结束时返回特定的退出代码,则它们可以实现org.springframework.boot.ExitCodeGenerator接口。
https://stackoverflow.com/questions/39370021
复制相似问题