In my previous post under Spring Core, I showed you guys, how to listed to application events, how to create and publish our own application event, and how to associate multiple event listeners to one particular event.
In this post under Spring Core, I will show with example how to order multiple application event listener associated with one particular application event.
We will the “@Order” annotation to the order the application event listeners. This annotation is applied at method level and it takes a number as an argument.
For our example we use the existing application event “ContextStoppedEvent” that is thrown when Spring stops its application context.
Below is the event listener class that have the code that should be executed when that event is generated.
ApplicationContextEventListener
package package34;
import org.springframework.context.event.ContextStoppedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextEventListener {
@EventListener(ContextStoppedEvent.class)
@Order(1)
public void contextStoppedEventListener1(ContextStoppedEvent contextStoppedEvent) {
System.out.println("Event Listener 1 responding");
}
@EventListener(ContextStoppedEvent.class)
@Order(2)
public void contextStoppedEventListener2(ContextStoppedEvent contextStoppedEvent) {
System.out.println("Event Listener 2 responding");
}
@Order(3)
@EventListener(ContextStoppedEvent.class)
public void contextStoppedEventListener3(ContextStoppedEvent contextStoppedEvent) {
System.out.println("Event Listener 3 responding");
}
}
As you can see from the above code, I have created three event listeners that will listen for “ContextStoppedEvent” event and execute the code when the event is generated.
We also annotated the methods with “@Order” annotation, passing an integer as an argument.
So based on the above code, the event listener methods are executed in the below order
1) contextStoppedEventListener1
2) contextStoppedEventListener2
3) contextStoppedEventListener3
In this way we can order the event listeners.
Below is the main code for your reference.
Main class
package package34;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan(basePackages = "package34")
public class Example34 {
public static void main(String[] args) {
ConfigurableApplicationContext configurableApplicationContext = new AnnotationConfigApplicationContext(Example34.class);
configurableApplicationContext.stop();
}
}