当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Spring Boot shutdown hook

问题描述:

How can I register/add a custom shutdown routine that shall fire when my Spring Boot application shuts down?

Scenario: I deploy my Spring Boot application to a Jetty servlet container (i.e., no embedded Jetty). My application uses Logback for logging, and I want to change logging levels during runtime using Logback's MBean JMX configurator. Its documentation states that to avoid memory leaks, on shutdown a specific LoggerContext shutdown method has to be called.

What are good ways to listen on Spring Boot shutdown events?

I have tried:

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

ConfigurableApplicationContext cac = SpringApplication.run(Example.class, args);

cac.addApplicationListener(new ApplicationListener<ContextClosedEvent>() {

@Override

public void onApplicationEvent(ContextClosedEvent event) {

logger.info("Do something");

}

});

}

but this registered listener does not get called when the application shuts down.

网友答案:

http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-application-exit

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.

网友答案:

Your listener is registered too late (that line will never be reached until the context has already closed). It should suffice to make it a @Bean.

分享给朋友:
您可能感兴趣的文章:
随机阅读: