I want to handle multiple events in one class, here's my example:
@Lazy(false)
@Component
public class EventListenerImpl {
@EventListener
public void handleContextRefreshedEvent(ContextRefreshedEvent event) {
LOGGER.log(event.getSource());
...
}
}
However this method is not being executed when my application starts.
In my applicationContext.xml
I have:
<context:annotation-config/>
<context:component-scan base-package="..."/>
which should be enough for @EventListener
to work, according to the documentation.
The old way of implementing ApplicationListener<ContextRefreshedEvent>
works just fine.
I'm using Spring 4.2.4.RELEASE.
Alright, this remains a total mystery for me. I bet it's some kind of wierd maven/ide caching issue, but anyway this worked for me after several restarts :
@Lazy(false)
@Component
public class EventListenerImpl {
@EventListener
public void whatever(final ContextRefreshedEvent event) {
event.getSource();
}
}
What I found might explain what @moonlightcheese observed:
If the event is published early in the application's lifecycle, it is not sent to the annotated @EventListener
method. If it is published later, it is sent to the method.
My work around was to ensure that the event is not published prior to the ContextRefreshedEvent
. I had my publisher class implement ApplicationListener<ContextRefreshedEvent>
, and published my event from the onApplicationEvent(ContextRefreshedEvent event)
override. Similar strategies could be used where the onApplicationEvent(ContextRefreshedEvent event)
override is used to gate publication.
It's possible that anything which changes the timing dynamics of the application startup could affect the behavior one way or the other.
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