Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 285
Abdull Avatar asked Oct 31 '14 15:10

Abdull


People also ask

How do you gracefully shut down a spring boot application?

With Graceful Shutdown Enabled. Or, properties file. Having this enabled, Spring Boot will wait for the current requests to complete before closing down the Application Context fully. Also, during the shutdown phase it will stop accepting new requests.

What is shutdown hook in Java?

A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently.

Which actuator endpoint is used to shutdown the application in spring boot?

Spring Boot Actuator comes with many production-ready features which include /shutdown endpoint. By default, all /shutdown endpoint is not enabled in the Actuator. To use this endpoint in our application, we should include spring-boot-starter-actuator starter and enable this endpoint in our application.


1 Answers

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.

like image 95
cfrick Avatar answered Oct 02 '22 22:10

cfrick