I have a Spring web application with two contexts: one (applicationContext
) built by ContextLoaderListener
and a second (webContext
) built by DispatcherServlet
.
Within the applicationContext
is a bean (org.springframework.security.authentication.DefaultAuthenticationEventPublisher
) that fires spring context events.
But the receiver for the event is defined in the webContext
. And that receiver did not get the event. (If put the receiver for test purpose in the applicationContext
then it get the event, but I can not do this, because I need the webContext
s for its functionality.)
So my question is, how to bridges the events from the applicationContext
to webContext
?
It's possible to create separate contexts and organize them in a hierarchy in Spring Boot. A context hierarchy can be defined in different ways in Spring Boot application.
To listen to a context event, a bean should implement the ApplicationListener interface which has just one method onApplicationEvent().
If you want run a job after Spring's context start, then you can use the ApplicationListener and the event ContextRefreshedEvent .
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.
I had the same problem, solved mine by moving the beans creating the event to web-context. However you can solve your problem by manually wiring your event listener, something like this (this code is not compiled therefore it is untested):
@Component
public class BeanInWebContext implements ApplicationListener<SomeEvent> {
@Autowired
private ApplicationContext webContext;
@PostConstruct
public void registerAsListener() {
// get parent context
AbstractApplicationContext appContext = (AbstractApplicationContext) webContext.getParent();
// register self as a listener, this method is in AbstractApplicationContext
appContext.addApplicationListener(this);
}
@Override
public void onApplicationEvent(SomeEvent event) {
}
}
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