java – Bean生命周期管理Spring Boot

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

From the docs:

The JSR-250 @PostConstruct and @PreDestroy annotations are generally considered best practice for receiving lifecycle callbacks in a modern Spring application. Using these annotations means that your beans are not coupled to Spring specific interfaces.

For details see Section 7.9.8, “@PostConstruct and @PreDestroy”

这些注释旨在放在一些init和cleanup方法上:

@PostConstruct
public void initAfterStartup() {
    ...
}

@PreDestroy
public void cleanupBeforeExit() {
    ...
}

也很有用:

Each SpringApplication will register a shutdown hook with the JVM to ensure that the ApplicationContext is closed gracefully on exit. All the standard Spring lifecycle callbacks (such as the DisposableBean interface, or the @PreDestroy annotation) can be used.

In addition, beans may implement the org.springframework.boot.ExitCodeGenerator interface if they wish to return a specific exit code when the application ends.

相关文章
相关标签/搜索