Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring ApplicationListener is not receiving events

I have the following ApplicationListener:

package org.mycompany.listeners;  import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextStartedEvent;  public class MyApplicationListener implements ApplicationListener<ContextStartedEvent> {    public MyApplicationListener() {     super();     System.out.println("Application context listener is created!");   }    /**    * {@inheritDoc}    */   public void onApplicationEvent(final ContextStartedEvent event) {     System.out.println("Context '" + event.getApplicationContext().getDisplayName() + "' is started!");   }  } 

And the following bean definition:

<bean name="myApplicationListener" class="org.mycompany.listeners.MyApplicationListener" /> 

I can see that bean is created as message from the constructor is printed, but context start event is never recieved. What am I missing?

like image 897
Andrey Adamovich Avatar asked Apr 20 '11 09:04

Andrey Adamovich


People also ask

What is ApplicationListener in spring?

As of Spring 3.0, an ApplicationListener can generically declare the event type that it is interested in. When registered with a Spring ApplicationContext , events will be filtered accordingly, with the listener getting invoked for matching event objects only.

How does spring boot handle events?

An event can have multiple listeners doing different work based on application requirements. There are two ways to define a listener. We can either use the @EventListener annotation or implement the ApplicationListener interface. In either case, the listener class has to be managed by Spring.

What is RequestHandledEvent event?

public class RequestHandledEvent extends ApplicationEvent. Event raised when a request is handled within an ApplicationContext. Supported by Spring's own FrameworkServlet (through a specific ServletRequestHandledEvent subclass), but can also be raised by any other web component.

What is ApplicationEventPublisher?

Interface ApplicationEventPublisher This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference. @FunctionalInterface public interface ApplicationEventPublisher. Interface that encapsulates event publication functionality.


1 Answers

ContextStartedEvent is published when you explicitly invoke ConfigurableApplicationContext.start() on the context. If you need an event that is published when context is initialized, use ContextRefreshedEvent.

See also:

  • 3.13.2 Standard and Custom Events
like image 155
axtavt Avatar answered Oct 05 '22 04:10

axtavt