Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bridge Spring Application Context events to an other context

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 webContexts for its functionality.)

So my question is, how to bridges the events from the applicationContext to webContext?

like image 459
Ralph Avatar asked Dec 16 '11 12:12

Ralph


People also ask

Can a Spring application have multiple contexts?

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.

Which of the following interfaces have to be implemented to get application context event notifications in the class?

To listen to a context event, a bean should implement the ApplicationListener interface which has just one method onApplicationEvent().

How can we invoke an action after loading a spring context?

If you want run a job after Spring's context start, then you can use the ApplicationListener and the event ContextRefreshedEvent .

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.


1 Answers

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) {
    }

}
like image 102
berserk81 Avatar answered Nov 07 '22 03:11

berserk81