Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @EventListener annotation doesn't work

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.

like image 842
Babken Vardanyan Avatar asked Feb 10 '16 11:02

Babken Vardanyan


2 Answers

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();
    }
}
like image 73
Babken Vardanyan Avatar answered Oct 24 '22 01:10

Babken Vardanyan


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.

like image 1
Jim Sermersheim Avatar answered Oct 24 '22 00:10

Jim Sermersheim