【问题标题】:Bean Lifecycle Management Spring BootBean 生命周期管理 Spring Boot
【发布时间】:2016-09-07 12:30:41
【问题描述】:

我目前正在尝试将 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 配置?

【问题讨论】:

  • 你想监听一些 Spring 上下文生命周期事件并在它们上管理你的线程吗?

标签: java spring tomcat


【解决方案1】:

From the docs:

JSR-250 @PostConstruct 和 @PreDestroy 注释通常被认为是在现代 Spring 应用程序中接收生命周期回调的最佳实践。使用这些注解意味着您的 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 注解)都可以使用。

此外,如果希望在应用程序结束时返回特定的退出代码,bean 可以实现 org.springframework.boot.ExitCodeGenerator 接口。

【讨论】: