SpringBoot – Executing method when  Application Starts and Periodically

When building an application, We might face an requirement that some tasks needs to be executed along with the application when the application Starts. Springboot has options available to make this happen.

@ApplicationReadyEvent
@ApplicationFailedEvent

What does these annotations do?
As the name suggests, when we use this annotation over a method, when the springboot application starts these methods will get executed along with the springboot startup.

When the application is fails on startup, ApplicationFailedEvent will get triggered.

@ContextRefreshedEvent
ContextRefreshedEvent annotation will also get executed when the springBoot application starts, But the difference between ApplicationReadyEvent and ContextRefreshedEvent is – ContextRefreshedEvent will get executed when ApplicationReadyEvent is getting intialized. So ContextRefreshedEvent will get executed even before ApplicationReadyEvent. (Refer here)

Now let us see an detailed example of using these annotations,

@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");
    }
}

When we execute this code,


Now let us make an error to make the application fail, so ApplicationFailedEvent will get executed,

@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(){   
        try{
            int i=0;
            i = i/0;
        }catch (Exception e){
            throw e;
        } 
    }
    
    @EventListener(ApplicationFailedEvent.class)
    public void EventListenerExecuteFailed(){
        System.out.println("Application Event Listener is Failed");
    }
}

on executing the above code, it should throw ArithmeticException and ApplicationFailedEvent should get executed,

 

By Sri

Leave a Reply

Your email address will not be published. Required fields are marked *