如何将Spring应用程序上下文事件桥接到其他上下文 [英] How to bridge Spring Application Context events to an other context

查看:96
本文介绍了如何将Spring应用程序上下文事件桥接到其他上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有两个上下文的Spring Web应用程序:由 ContextLoaderListener 构建的一个( applicationContext )和第二个 webContext )由 DispatcherServlet 构建。



code> applicationContext 是一个启动弹簧上下文事件的bean( org.springframework.security.authentication.DefaultAuthenticationEventPublisher )。



但事件的接收者在 webContext 中定义。那个接收者没有得到这个事件。 (如果将接收者用于测试目的在 applicationContext 中,那么它会得到该事件,但是我不能这样做,因为我需要 webContext s的功能。)



所以我的问题是如何桥接来自 applicationContext to webContext

解决方案

我有同样的问题,解决了我的移动豆创建事件到web上下文。但是您可以通过手动连接事件监听器来解决您的问题,这样做(此代码未编译,因此未经测试):

  @Component 
public class BeanInWebContext implements ApplicationListener< SomeEvent> {

@Autowired
private ApplicationContext webContext;

@PostConstruct
public void registerAsListener(){
//获取父上下文
AbstractApplicationContext appContext =(AbstractApplicationContext)webContext.getParent();
//注册自身作为监听器,此方法在AbstractApplicationContext
appContext.addApplicationListener(this);
}

@Override
public void onApplicationEvent(SomeEvent event){
}

}


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?

解决方案

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

}

这篇关于如何将Spring应用程序上下文事件桥接到其他上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆