java - Spring Boot 关闭钩子(Hook)

标签 java spring-boot

如何注册/添加一个自定义关闭例程,该例程在我的 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");
        }
    });
}

但是当应用程序关闭时,这个注册的监听器不会被调用。

最佳答案

https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#features.spring-application.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.

关于java - Spring Boot 关闭钩子(Hook),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26678208/

相关文章:

spring-boot - 如果由于消费者处理消息时出错而未发送手动确认,那么如何以及何时重新传递 Kafka 消息?

java - 如何手动添加 jlabels 到滚动 Pane ?

java - Spring Boot 过滤器未返回正确的响应

java - 不使用正则表达式的 Java 字符串搜索库

java - 将字符串从数据库传递给 drawString()

java - Spring Boot 微服务在 docker 容器内运行时启用 Https

java - 在 spring boot 端点上使用自定义 jackson 映射器

java - mock bean 并不总是有效

java - 如何停止闹钟声音

java - 从注释处理器生成 Spring 组件