Application events · Topic 5 of 5
Built-in lifecycle events
Definition​
Spring publishes events about its own life: ContextRefreshedEvent when the application is ready and ContextClosedEvent when it shuts down. Listen to them to start work after startup or to clean up on shutdown. Spring Boot adds ApplicationReadyEvent.
Example code​
Hooking into startup and shutdown
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
class Lifecycle {
@EventListener
void started(ContextRefreshedEvent event) { System.out.println("application is ready: warm the caches"); }
@EventListener
void stopping(ContextClosedEvent event) { System.out.println("application is closing: flush and say goodbye"); }
}
@ComponentScan
class Demo {
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Demo.class)) {
System.out.println("doing work");
}
}
}
// Output:
// application is ready: warm the caches
// doing work
// application is closing: flush and say goodbye
Finished this page? Track your progress (saved only in your browser).