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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With