Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Know Which EventListener will Execute First in Spring

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?

like image 354
Developer Guy Avatar asked Jan 16 '18 19:01

Developer Guy


2 Answers

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.

like image 141
gohil90 Avatar answered Sep 21 '22 04:09

gohil90


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.

like image 37
Andrei Amarfii Avatar answered Sep 19 '22 04:09

Andrei Amarfii