title: Spring Boot shutdown hook
body: <p>How can I register/add a custom shutdown routine that shall fire when my Spring Boot application shuts down?</p>
  
  <p>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. <a href="http://logback.qos.ch/manual/jmxConfig.html#leak" rel="noreferrer">Its documentation states that to avoid memory leaks, on shutdown a specific LoggerContext shutdown method has to be called</a>.</p>
  
  <p>What are good ways to listen on Spring Boot shutdown events?</p>
  
  <p>I have tried: </p>
  
  <pre><code>public static void main(String[] args) throws Exception {
      ConfigurableApplicationContext cac = SpringApplication.run(Example.class, args);
  
      cac.addApplicationListener(new ApplicationListener&lt;ContextClosedEvent&gt;() {
  
          @Override
          public void onApplicationEvent(ContextClosedEvent event) {
              logger.info("Do something");
          }
      });
  }
  </code></pre>
  
  <p>but this registered listener does not get called when the application shuts down.</p>