Chaining multiple application event listener

In previous post under Spring Core, I showed
1) how to listen for events generated from application context
2) how to generate and listen for custom application event.

In this post, I will show with example how to chain multiple event listener for a particular application event

For our example, I will take “ContextStoppedEvent” event which is generated by Spring application context when it is stopped.

Below is the event listener class

ApplicationContextEventListener

package package33;

import org.springframework.context.event.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
public class ApplicationContextEventListener {
    @EventListener(ContextStoppedEvent.class)
    public void contextStoppedEventListener1(ContextStoppedEvent contextStoppedEvent) {
        System.out.println("Context Stopped Event Listener 1 responding");
    }

    @EventListener(ContextStoppedEvent.class)
    public void contextStoppedEventListener2(ContextStoppedEvent contextStoppedEvent) {
        System.out.println("Context Stopped Event Listener 2 responding");
    }
}

In the above class, I have added two methods and annotated them with “@EventListener” annotation. The event type passed as argument to both annotations is same which is “ContextStoppedEvent”.

As a result of which when the spring application context is stopped, both the methods are chained and executed.

There is no specific order in which these method are chained and executed.

Below is the main class which closes the application context and causes Spring to publish “ContextStoppedEvent” event.

Main class

package package33;

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

@ComponentScan(basePackages = "package33")
public class Example33 {
    public static void main(String[] args) {
        ConfigurableApplicationContext configurableApplicationContext = new AnnotationConfigApplicationContext(Example33.class);
        configurableApplicationContext.stop();
    }
}

In this way we can chain multiple event listeners for a particular event.

Leave a comment