如何注册/添加在我的 Spring Boot 应用程序关闭时触发的自定义关闭例程?
场景:我将我的 Spring Boot 应用程序部署到 Jetty servlet 容器(即,没有嵌入式 Jetty)。我的应用程序使用 Logback 进行日志记录,我想在运行时使用 Logback 的 MBean JMX 配置器更改日志记录级别。 它的文档指出,为了避免内存泄漏,关闭时必须调用特定的 LoggerContext 关闭方法。
监听 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");
}
});
}
但是当应用程序关闭时,这个注册的侦听器不会被调用。
原文由 Abdull 发布,翻译遵循 CC BY-SA 4.0 许可协议
https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#features.spring-application.application-exit