Events
SpringApplication publishes an event at each step of the start, as Spring Boot does. It also keeps the application's availability: whether it is alive and whether it takes traffic.
Why
Some code has to act at a precise moment: once the properties are known but before any bean exists, or once the application is ready to serve. Events give these moments a name, so the code does not depend on how the start is written. Availability answers the two questions an orchestrator such as Kubernetes asks: should this instance be restarted, and should it get requests now?
Example
// Fill the cache once the application is up, without delaying the start.
@Component()
class Warmup {
Warmup(this.cache);
final Cache cache;
@EventListener()
void onReady(ApplicationReadyEvent event) => cache.fill();
}
// Before any bean exists: only a listener on the application sees this.
@SpringBootApplication()
void main(List<String> args) => (springApplication
..addListener<ApplicationEnvironmentPreparedEvent>(
(event) => print('Profiles: ${event.environment.activeProfiles}'),
))
.run(args);
The events, in order
| Event | When | Carries |
|---|---|---|
ApplicationStartingEvent |
The run has begun; nothing is read yet | args |
ApplicationEnvironmentPreparedEvent |
Properties and profiles are known; no context yet | environment |
ApplicationContextInitializedEvent |
The context exists and the initializers have run; no bean definition loaded | applicationContext |
ApplicationPreparedEvent |
The bean definitions are loaded; no bean created | applicationContext |
ContextRefreshedEvent |
Every singleton is created (the context's own event) | |
ApplicationStartedEvent |
The context is started; the runners come next | applicationContext, timeTaken |
AvailabilityChangeEvent with LivenessState.correct |
Right after ApplicationStartedEvent |
state |
ApplicationReadyEvent |
The runners are done | applicationContext, timeTaken |
AvailabilityChangeEvent with ReadinessState.acceptingTraffic |
Right after ApplicationReadyEvent |
state |
ApplicationFailedEvent |
Instead of the rest, when the start or a runner fails; before the failure report | applicationContext (may be null), exception |
Every one of them extends SpringApplicationEvent, which carries the args.
Who receives what
- The events up to
ApplicationPreparedEventhappen before any bean exists, so an@EventListenermethod never receives them. Only listeners registered on the application do:springApplication.addListener<E>(...),addListeners([...])orSpringApplication(listeners: [...]). - From
ApplicationPreparedEventon, those listeners are also listeners of the context, so they receive its events too (ContextClosedEvent, for example). ApplicationStartedEvent,ApplicationReadyEvent, the availability events and theApplicationFailedEventof a failing runner go through the context, so@EventListenermethods andApplicationListenerbeans receive them.
Most applications only need ApplicationReadyEvent, in a bean.
// A listener on the application, with an order among the others.
springApplication
..addListener<ApplicationStartingEvent>((event) => print('starting'), order: 0)
..addListeners([
ApplicationListenerAdapter.of<ApplicationFailedEvent>(
(event) => alerts.send('Start failed: ${event.exception}'),
),
]);
Availability
| State | Values | Set by SpringApplication |
|---|---|---|
LivenessState |
correct, broken |
correct after ApplicationStartedEvent |
ReadinessState |
acceptingTraffic, refusingTraffic |
acceptingTraffic after ApplicationReadyEvent |
A broken application cannot recover by itself and should be restarted. An application that refuses traffic only gets no requests for a while.
The applicationAvailability bean (ApplicationAvailability) keeps the last state of each kind:
| Member | Meaning |
|---|---|
livenessState |
The last LivenessState; broken before the first |
readinessState |
The last ReadinessState; refusingTraffic before the first |
getState<S>(defaultState) |
The last state of type S, or defaultState |
getLastChangeEvent<S>() |
The last event of type S, or null |
Change a state by publishing an event:
// Tell the load balancer to send requests elsewhere while the cache rebuilds.
@Component()
class CacheRebuild {
CacheRebuild(this.events, this.cache);
final ApplicationEventPublisher events;
final Cache cache;
Future<void> rebuild() async {
AvailabilityChangeEvent.publish(events, ReadinessState.refusingTraffic);
await cache.rebuild();
AvailabilityChangeEvent.publish(events, ReadinessState.acceptingTraffic);
}
}
// Read the current state anywhere.
if (availability.readinessState == ReadinessState.acceptingTraffic) { ... }
The actuator's liveness and readiness health groups answer from these states (see spring_boot_actuator). The bean comes from ApplicationAvailabilityAutoConfiguration; your own ApplicationAvailability bean replaces it.
In Spring (Java)
The same events in the same order, and the same availability types (LivenessState.CORRECT, ReadinessState.ACCEPTING_TRAFFIC). Listeners for the early events are added with addListener on the application instead of META-INF/spring.factories.