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?
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.
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.
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.
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.
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:
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