Application Listener in Spring Boot bases its events handling on beans implementing org.springframework.context.ApplicationListener interface. It defines only one method, onApplicationEvent which is trigerred when an event is sent. This interface can be generic by specifying the event to which it has to be applied.

Spring will filter itself which listeners can receive given event. Event is represented by org.springframework.context.ApplicationEvent instances.

Registering ApplicationListener via spring.factories

Implement listener using 2 Steps:

  1. Create custom class implementing ApplicationListerner interface
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;

public class TestListeners implements ApplicationListener<ApplicationEvent> {

  @Override
  public void onApplicationEvent(ApplicationEvent event) {
    System.out.println("Event ::: "+event);
    
  }

}

2. Create spring.factories file in following path src/main/resources/META-INF/spring.factories and reference your listener(s) by using the org.springframework.context.ApplicationListenerkey, as shown in the following example:

org.springframework.context.ApplicationListener=com.talksinfo.springboot.listeners.TestListeners

When above Applicationlistener in Spring Boot is implemented, Application events are sent in the following order, as your application runs:

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

In addition to these, the following events are also published after ApplicationPreparedEvent and before ApplicationStartedEvent:

  1. ContextRefreshedEvent is sent when an ApplicationContext is refreshed.
  2. WebServerInitializedEvent is sent after the WebServer is ready. ServletWebServerInitializedEvent and ReactiveWebServerInitializedEvent are the servlet and reactive variants respectively.

Console will look something like below when Applicationlistener in Spring Boot is implemented,

Event ::: org.springframework.boot.context.event.ApplicationStartingEvent[[email protected]]
Event ::: org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent[[email protected]]

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::  (v2.2.0.BUILD-SNAPSHOT)

Event ::: org.springframework.boot.context.event.ApplicationContextInitializedEvent[[email protected]]
2019-07-28 17:05:14.050  INFO 19260 --- [           main] c.talksinfo.springboot.BankApplication   : Starting BankApplication on LAPTOP-D2GVO184 with PID 19260 (E:\Workspace\BlogWorkspace\SpringBoot\bankservices\target\classes started by vrdha in E:\Workspace\BlogWorkspace\SpringBoot\bankservices)
2019-07-28 17:05:14.053  INFO 19260 --- [           main] c.talksinfo.springboot.BankApplication   : No active profile set, falling back to default profiles: default
Event ::: org.springframework.boot.context.event.ApplicationPreparedEvent[[email protected]]
2019-07-28 17:05:14.693  INFO 19260 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-07-28 17:05:14.700  INFO 19260 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-07-28 17:05:14.700  INFO 19260 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.21]
2019-07-28 17:05:14.757  INFO 19260 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-07-28 17:05:14.757  INFO 19260 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 662 ms
2019-07-28 17:05:14.900  INFO 19260 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
Context Refreshed Event ::::: org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.boot.web.ser[email protected]3e3047e6, started on Sun Jul 28 17:05:14 IST 2019]
Event ::: org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.boot.web.ser[email protected]3e3047e6, started on Sun Jul 28 17:05:14 IST 2019]
2019-07-28 17:05:15.020  INFO 19260 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
Event ::: org.springframework.boot.web.servlet.context.ServletWebServerInitializedEvent[sour[email protected]25230246]
2019-07-28 17:05:15.023  INFO 19260 --- [           main] c.talksinfo.springboot.BankApplication   : Started BankApplication in 1.207 seconds (JVM running for 1.779)
Event ::: org.springframework.boot.context.event.ApplicationStartedEvent[[email protected]]
Event ::: org.springframework.boot.context.event.ApplicationReadyEvent[[email protected]]

Conclusion

In this article, we’ve explored the various built-in events in Spring. In addition, we’ve seen ways to listen to events registering in spring.factories file.

 

Please follow and like us:
error