Using ApplicationReadyEvent to run code at Spring Boot startup

The ApplicationReadyEvent (https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/context/event/ApplicationReadyEvent.html) can be used to trigger application code when a Spring Boot application is started. Let’s see how to do it in practice.

package com.example.testrest;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component public class ApplicationStartup implements ApplicationListener < ApplicationReadyEvent > {
  @Override public void onApplicationEvent(final ApplicationReadyEvent event) {
    System.out.println("Application started!");
    return;
  }
}

When you start the application, you will see from the Server Logs:

2021-05-12 16:18:50.341  INFO 22200 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path '' 2021-05-12 16:18:50.349  INFO 22200 --- [           main] com.example.testrest.DemoApplication     : Started DemoApplication in 1.166 seconds (JVM running for 1.477) Application started!

If you want to capture multiple events, such as a failure in application startup, you can use @EventListener annotation which can be associated with a ContextRefreshedEvent, an ApplicationReadyEvent and an ApplicationFailedEvent:

@SpringBootApplication
@EnableScheduling
public class MyApplication {
  public static void main(String[] args) throws Exception {
    SpringApplication.run(MyApplication.class, args);
  }

  @EventListener(ContextRefreshedEvent.class)
  public void ContextRefreshedEventExecute() {
    System.out.println("Context Event Listener is getting executed");
  }

  @EventListener(ApplicationReadyEvent.class)
  public void EventListenerExecute() {
    System.out.println("Application Ready Event is successfully Started");
  }

  @EventListener(ApplicationFailedEvent.class)
  public void EventListenerExecuteFailed() {
    System.out.println("Application Event Listener is Failed");
  }
}

In terms of configuration, you don’t need any special library to trigger the ApplicationReadyEvent. Just include the web starter:

<?xml version="1.0" encoding="UTF-8"?><project>
   <dependency>
       	
      <groupId>org.springframework.boot</groupId>
       	
      <artifactId>spring-boot-starter-web</artifactId>
       
   </dependency>
    
</project>