Both ApplicationStartedEvent and ApplicationReadyEvent executes once service is started but there is little difference that ApplicationReadyEvent executes when application is ready to serve the request. Will see the implementation for both in below code.
Since both are starting after application is up, we can use annotation based listener in this case. We will see the implementation In two different ways.
Since both are starting after application is up, we can use annotation based listener in this case. We will see the implementation In two different ways.
Using Annotation
To use annotation based listener we can define below code in any spring managed bean, like Component, Configuration etc.@EventListener(ApplicationReadyEvent.class) public void applicationReadyEvent() { System.out.println("Executing ApplicationReadyEvent..."); } @EventListener(ApplicationStartedEvent.class) public void applicationStartedEvent() { System.out.println("Executing ApplicationStartedEvent..."); }
Registering with SpringApplication
Below code shows the event listener creation with SpringApplication.@SpringBootApplication public class SpringBootTutorialApplication implements AsyncConfigurer{ public static void main(String[] args) { SpringApplication app = new SpringApplication(SpringBootTutorialApplication.class); app.addListeners((ApplicationReadyEvent event)->{ System.out.println("Executing ApplicationReadyEvent..."); }); app.addListeners((ApplicationStartedEvent event)->{ System.out.println("Executing ApplicationStartedEvent..."); }); //start the application app.run(args); }
Output
Event execution statements are highlighted in below output2019-10-26 16:22:24.136 INFO 14298 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' 2019-10-26 16:22:24.139 INFO 14298 --- [ main] com.demo.SpringBootTutorialApplication : Started SpringBootTutorialApplication in 6.076 seconds (JVM running for 6.594) Executing ApplicationStartedEvent... Executing ApplicationReadyEvent...
Comments
Post a Comment