Saturday, January 6, 2024

SpringBoot Application Event Listeners

When a spring boot application starts few events occurs in below order
  • ApplicationStartingEvent
  • ApplicationEnvironmentPreparedEvent
  • ApplicationContextInitializedEvent
  • ApplicationPreparedEvent
  • ApplicationStartedEvent
  • ApplicationReadyEvent
These events can be listened by adding an application event listener to the spring boot application as below

  • Create a class implementing ApplicationListener<SpringApplicationEvent> interface
public class ApplicationEventListener implements ApplicationListener<SpringApplicationEvent> {
@Override
public void onApplicationEvent(SpringApplicationEvent event) {
log.info( " > " + event );
}
}
  • Register the above listener class to the spring boot application main class as
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(MyApplication .class);
app.addListeners(new ApplicationEventListener());
app.run(args);
}
}
  • Start the application and all the above events can be seen in the console logs.

No comments:

Post a Comment

SpringBoot Application Event Listeners

When a spring boot application starts few events occurs in below order ApplicationStartingEvent ApplicationEnvironmentPreparedEvent Applicat...