如何注册/添加一个自定义关闭例程,该例程在我的 Spring Boot 应用程序关闭时触发?
场景:我将 Spring Boot 应用程序部署到 Jetty servlet 容器(即,没有嵌入式 Jetty)。我的应用程序使用 Logback 进行日志记录,我想在运行时使用 Logback 的 MBean JMX 配置器更改日志记录级别。 Its documentation states that to avoid memory leaks, on shutdown a specific LoggerContext shutdown method has to be called .
监听 Spring Boot 关闭事件的好方法是什么?
我试过了:
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");
}
});
}
但是当应用程序关闭时,这个注册的监听器不会被调用。
最佳答案
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.
关于java - Spring Boot 关闭钩子(Hook),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26678208/