How to set the order of event listeners in Spring?

In Spring, the order of event listeners is determined by the Order interface. The interface defines a getOrder() method that returns an integer value indicating the listener’s order. The listener with the smallest value has a higher priority and will be called earlier.

If you wish to set the order of event listeners, you can have your listeners implement the Ordered interface and return the relevant priority value in the getOrder() method.

@Component
public class MyEventListener implements ApplicationListener<MyEvent>, Ordered {

  @Override
  public void onApplicationEvent(MyEvent event) {
    // 处理事件逻辑
  }

  @Override
  public int getOrder() {
    // 设置监听器的优先级,值越小优先级越高
    return 1;
  }
}

In the example above, MyEventListener implements the Ordered interface and returns 1 in the getOrder() method, indicating a priority of 1. If there are multiple event listeners, you can set different priority values as needed to determine the order in which they are called.

Note: If the listeners do not implement the Ordered interface, they will be invoked in the order they were registered.

bannerAds