Skip to main content

ApplicationContextInitializedEvent Code Example

ApplicationContextInitializedEvent provides you access to ApplicationContext and SpringApplication using which you can do many things like adding listeners at runtime, invoking events etc. In below code we will see how to register this event and fail the application if it finds the value true for given property.

SpringBootTutorialApplication.java

public class SpringBootTutorialApplication{
 public static void main(String[] args) {
  SpringApplication app = new SpringApplication(SpringBootTutorialApplication.class);
  
  //register ApplicationContextInitializedEvent event
  app.addListeners((ApplicationContextInitializedEvent event)->{
   System.out.println("Executing ApplicationContextInitializedEvent...");
   //get the property value 
   String shouldFailed = event.getApplicationContext()
     .getEnvironment().getProperty("should.app.failed");
   if("true".equals(shouldFailed)) {
    //invoke failed event
    event.getApplicationContext()
     .publishEvent(ApplicationFailedEvent.class);
   }
  });
  
  //register ApplicationFailedEvent event
  app.addListeners((ApplicationFailedEvent event)->{
   System.out.println("Executing ApplicationFailedEvent...");
  });
  //start the application
  app.run(args);
 }

application.properties

should.app.failed

Output

Below output shows that both the events are executed and failed event has caused the failure of application.

 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.9.RELEASE)

Executing ApplicationContextInitializedEvent...
Executing ApplicationFailedEvent...
2019-10-26 12:58:06.146 ERROR 12343 --- [           main] o.s.boot.SpringApplication               : Application run failed

java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@358c99f5, started on Thu Jan 01 05:30:00 IST 1970

Comments

Post a Comment