I inherited some code that uses multiple Spring EventListeners to handle a specific event. I noticed that in different environments, the EventListeners executed in a different order when an event is published.
For example, say I have 2 EventListeners:
@EventListener
@Async
public void doSomethingForEvent(SomeEvent event)
and
@EventListener
@Async
public void doAnotherThingForEvent(SomeEvent event)
In one environment, doSomethingForEvent
executed before doAnotherThingForEvent
and in another environment, it was vice versa.
So my question is, is there a way to know what order they will execute in? Is it a random order because of the @Async
annotation, or is there a way to specify the order?
It is also possible to define the order in which listeners for a certain event are to be invoked. To do so, add Spring's common @Order annotation alongside this event listener annotation.
As per the EventListener
document, you can use @Order
annotation and give different values to define order (lower number have the higher priority)
@EventListener
@Order(0)
@Async
public void doSomethingForEvent(SomeEvent event)
and
@EventListener
@Order(1)
@Async
public void doAnotherThingForEvent(SomeEvent event)
In above case, doSomethingForEvent
will executed first and then doAnotherThingForEvent
listener always.
check the javadoc of @EventListener
It is also possible to define the order in which listeners for a certain event are to be invoked. To do so, add Spring's common @Order annotation alongside this event listener annotation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With