28

I have several services that are listening for Spring events to make changes to my underlying data model. These all work by implementing ApplicationListener<Foo>. Once all of the Foo listeners modify the underlying data model, my user interface needs to refresh to reflect the changes (think fireTableDataChanged()).

Is there any way to ensure that a specific listener for Foo is always last? Or is there any way to call a function when all other listeners are done? I'm using annotation based wiring and Java config, if that matters.

Luke
  • 3,742
  • 4
  • 31
  • 50
  • 1
    Can you try implementing [`Ordered`](http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/core/Ordered.html) in each of your listeners and adjust order appropriately? – Tomasz Nurkiewicz Jun 05 '12 at 15:55
  • @TomaszNurkiewicz That looks promising, I'll try it in a second. – Luke Jun 05 '12 at 15:57
  • @TomaszNurkiewicz care you put that in an answer so I can give you credit for it? That worked great! – Luke Jun 05 '12 at 16:12
  • Done, glad I could help. Can you make sure I haven't messed up the order (lowest goes first, not last)? – Tomasz Nurkiewicz Jun 05 '12 at 18:59
  • @TomaszNurkiewicz Yes, lowest integer is highest priority. Ordered.LOWEST_PRECEDENCE is Integer.MAX_VALUE. – Luke Jun 05 '12 at 19:11

1 Answers1

45

All your beans implementing ApplicationListener should also implement Ordered and provide reasonable order value. The lower the value, the sooner your listener will be invoked:

class FirstListener implements ApplicationListener<Foo>, Ordered {
    public int getOrder() {
        return 10;
    }
    //...
}

class SecondListener implements ApplicationListener<Foo>, Ordered {
    public int getOrder() {
        return 20;
    }
    //...
}

class LastListener implements ApplicationListener<Foo>, Ordered {
    public int getOrder() {
        return LOWEST_PRECEDENCE;
    }
    //...
}

Moreover you can implement PriorityOrdered to make sure one of your listeners is always invoked first.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • Is it possible that order is ignored for auth event listeners? I had `CustomAuthListener implements ApplicationListener, Ordered`, but the `return LOWEST_PRECEDENCE` was never called. Luckily I just had to listen to `InteractiveAuthenticationSuccessEvent` instead of `AuthenticationSuccessEvent` to fix my problem. – Vlastimil Ovčáčík Feb 26 '16 at 07:08
  • i wish i have found this answer on time. So remember ALL of the beans should implement Ordered. Otherwise the will be executed after the ordered once even after the LOWEST_PRECEDENCE Bean – KiteUp Jun 21 '19 at 11:27