java – Bean生命周期管理Spring Boot

我目前正在尝试将 Spring Boot应用程序部署到外部Tomcat实例中,并且遇到了一些关于如何最好地管理某些事物的实例化的问题.


public class MyClass extends SpringBootServletInitializer{

public ThreadPool pool(){
    return new ThreadPool();

public BackgroundThread setupInbox() {
    BackgroundThread inbox = new BackgroundThread(pool());
    return inbox;

protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(MyClass.class);

public static void main(String[] args) throws Exception {, args);



正在部署的* .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”


public void initAfterStartup() {

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.