Friday 27 July 2018

Spring boot: Listening to exit code events

Spring boot fires an ExitCodeEvent, when an application exit code has been determined from an ExitCodeGenerator.

Example
                  @EventListener
                  public void exitCodeEvent(ExitCodeEvent event) {
                  System.out.println("*************************************");
                           System.out.println("exit code: " + event.getExitCode());
                  System.out.println("*************************************");
                  }

Above method is fired, when an application exit code is determined from ExitCodeGenerator.

Application.java
package com.sample.myApp;

import org.springframework.boot.ExitCodeEvent;
import org.springframework.boot.ExitCodeGenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.EventListener;

@SpringBootApplication
public class Application {

 public static void main(String[] args) {
  ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class, args);

  System.out.println("Closing Application Context");

  int exitCode = SpringApplication.exit(applicationContext);

  System.out.printf("Application Context is exited with : %d", exitCode);

 }

 @Bean
 public ExitCodeGenerator exitCodeGenerator10() {
  return () -> {
   System.out.println("Returning exit code 10");
   return 10;
  };

 }

 @Bean
 public ExitCodeEventModel getModel() {
  return new ExitCodeEventModel();
 }

 private static class ExitCodeEventModel {

  public ExitCodeEventModel() {
   System.out.println("Instantiating ExitCodeEventModel object");
  }

  @EventListener
  public void exitCodeEvent(ExitCodeEvent event) {
   System.out.println("*************************************");
   System.out.println("exit code: " + event.getExitCode());
   System.out.println("*************************************");
  }
 }
}

Output
Instantiating ExitCodeEventModel object
Closing Application Context
Returning exit code 10
*************************************
exit code: 10
*************************************
Application Context is exited with : 10

Total project structure looks like below.






Previous                                                 Next                                                 Home

No comments:

Post a Comment