Listening to ApplicationContext events

In this post under Spring Core, I will explain with example how to listen to ApplicationContext events.

The Spring framework when creates/stops/refresh an ApplicationContext, it generates certain events and we as a developer can listen to those events and add our custom logic so that it can be executed.

For our example, I will create the below listener class

Listener

package package31;

import org.springframework.context.event.*;
import org.springframework.stereotype.Component;

@Component
public class ApplicationContextEventListener {
    @EventListener(ContextRefreshedEvent.class)
    public void contextRefreshedInitializedEventListener(ContextRefreshedEvent contextStartedEvent) {
        System.out.println("Application Context Refreshed/Initialized");
    }

    @EventListener(ContextStoppedEvent.class)
    public void contextStoppedEventListener(ContextStoppedEvent contextStoppedEvent) {
        System.out.println("Application Context Stopped");
    }

    @EventListener(ContextClosedEvent.class)
    public void contextClosedEventListener(ContextClosedEvent contextClosedEvent) {
        System.out.println("Application Context Closed");
    }

    @EventListener(ContextStartedEvent.class)
    public void contextStartedEventListener(ContextStartedEvent contextStartedEvent) {
        System.out.println("Application Context Started");
    }
}

As you can see from the above code, we are using “@EventListener” annotation to mark a method that has to be executed when an event occurs.

We also mention at what event a particular method is to be executed by passing the class object of that event as an argument to “@EventListener” annotation.

So in the above code
1) “contextRefreshedInitializedEventListener” is called when “ContextRefreshedEvent” event is generated
2) “contextStoppedEventListener” is called when “ContextStoppedEvent” event is generated
3) “contextClosedEventListener” is called when “ContextClosedEvent” event is generated
4) “contextStartedEventListener” is called when “ContextStartedEvent” event is generated

In this way we can listen and perform some actions when ApplicationContext events are generated.

Below is the complete main class for your reference

Main class

package package31;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan(basePackages = "package31")
public class Example31 {
    public static void main(String... args) {
        ConfigurableApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example31.class);
        applicationContext.stop();
        applicationContext.start();
        applicationContext.close();
    }
}

We can close, start, and stop the applicationContext by calling corresponding methods.

Leave a comment