SpringBoot – @ApplicationReadyEvent, @ApplicationFailedEvent and @ContextRefreshedEvent

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,

When we execute this code,


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

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

 

Read More