Spring application events - apinazo/booter GitHub Wiki

Overview

The project implements some examples of how to listen to the Spring application events and how to configure the listeners.

Spring application live cycle

As stated in the Spring reference guide, the application events are sent in this order:

  • ApplicationStartingEvent: at the start of a run but before any processing, except for the registration of listeners and initializers.
  • ApplicationEnvironmentPreparedEvent: when the Environment to be used in the context is known but before the context is created.
  • ApplicationPreparedEvent: just before the refresh is started but after bean definitions have been loaded.
  • ApplicationStartedEvent: after the context has been refreshed but before any application and command-line runners have been called.
  • ApplicationReadyEvent: after any application and command-line runners have been called. It indicates that the application is ready to service requests.
  • ApplicationFailedEvent: is sent if there is an exception on startup.

Implementing application listeners

Before context is available

Events of this kind:

  • ApplicationStartingEvent
  • ApplicationEnvironmentPreparedEvent
  • ApplicationPreparedEvent

Some events ocurr before the Spring context is ready, so they can't be beans nor use any other Spring beans. Thus they have to be configured in special ways.

They both are complementary - you can use either one of them but only one.

spring.factories

This special file can be used to register an ApplicationListener. The file is located at: resources/META-INF/spring.factories.

A listener is registered as in the example:

# Listeners that are initialized before context is ready.
org.springframework.context.ApplicationListener=es.apinazo.booter.events.ApplicationPreparedEventListener

At app building

Alternatively, the listeners can be registered when the SpringApplication is being built:

SpringApplication app = new SpringApplication(BooterApplication.class);

app.addListeners(
    new ApplicationStartingEventListener(),
    new ApplicationEnvironmentPreparedEventListener());

After context is available

Events of this kind:

  • ApplicationFailedEvent
  • ApplicationReadyEvent
  • ApplicationStartedEvent

In this case, registration can be done in two ways:

  • In the app building with addListeners().
  • Or with a bean that implements ApplicationListenerof the event to listen.

The second way is shown in this example:

@Slf4j
@Component
public class ApplicationStartedEventListener implements ApplicationListener<ApplicationStartedEvent> {

    @Override
    public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
        log.info("[EVENTS] Caught ApplicationStartedEvent");
    }
}

References