2023-02-21

Spring Boot: Application Event Lifecycle

 With @EventListener, we can quickly turn a component's method into an event listener. Spring Boot has some predefined events we can tap into; they mark milestones in the application lifecycle.

  1. ApplicationStartingEvent
    Only the bootstrap context has been created, and "java.awt.headless" is turned off unless explicitly enabled externally.
  2. ApplicationEnvironmentPreparedEvent
    The environment sources are parsed and configured.
    Now you still have the opportunity to alter the environment, as the binding is a later step.
  3. ApplicationContextInitializedEvent
    Context is prepared, the environment is applied, and initializers have been executed. After this event, the bootstrap context is discarded.
  4. ApplicationPreparedEvent
    Beans were loaded, the magic happened.
  5. ApplicationStartedEvent
    The application context is refreshed, and we're alive.
    After this event is published, the liveness state is set to "correct" since there were no failures during initialization.
  6. On error between steps 2-5, an ApplicationFailedEvent is published before the shutdown hook is executed.
  7. ApplicationReadyEvent
    The startup is done, measurements are taken, startup info is logged, and runners are executed (command line or job). The readiness state is set to "accepting traffic" to let external actors know we're online.
After the started event, not much happens that affect us if we are making a standard application, so if we want to load some data that we couldn't or wouldn't initialize lazily on its own service, this is the spot.