如何将Spring Application Context事件与其他上下文联系起来

Ral*_*lph 16 java events spring

我有一个带有两个上下文的Spring Web应用程序:一个(applicationContext)构建,ContextLoaderListener另一个(webContext)构建DispatcherServlet.

applicationContext一个bean(org.springframework.security.authentication.DefaultAuthenticationEventPublisher)中,它触发spring上下文事件.

但是事件的接收器是在webContext.那个接收器没有得到这个事件.(如果将接收器用于测试目的,applicationContext那么它就会得到事件,但我不能这样做,因为我需要webContexts来实现它的功能.)

所以我的问题是,如何将事件与之结合applicationContext起来webContext

小智 9

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

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

}
Run Code Online (Sandbox Code Playgroud)


Sha*_*eep 3

尝试将事件发布者移动到 Web 上下文文件,它应该在整个应用程序上下文中具有可见性。在父应用程序上下文中配置方法安全性时,也会出现类似的问题。父应用程序上下文(由 加载ContextLoaderListener)不知道子(Web)上下文。

如果您确实不需要两者之间的父子关系,也可以对整个应用程序使用单个应用程序上下文。通常它只是碍事,如果所有 bean 都定义在同一个空间中,那就更容易了。