【问题标题】:Spring Event and Scope requestSpring 事件和范围请求
【发布时间】:2013-02-15 11:21:30
【问题描述】:

我想在我的 Web 应用程序中使用 Spring Event 与我的 bean “对话”。

因此,例如,我的触发事件的 bean 是这样的:

@Controller
@Scope("request")
@KeepAlive
public class Controller extends InitializingBean, ApplicationEventPublisherAware {

private ApplicationEventPublisher applicationEventPublisher;    

public void test() {
  applicationEventPublisher.publishEvent(new TestEvent(this));
}

}

而我的监听事件是这样的:

@Component
@Scope("request")
@KeepAlive
public class Module implements ApplicationListener<TestEvent> {

    @Override
    public void onApplicationEvent(TestEvent event) {

    }

}

最重要的一点是这些bean是作用域请求,因为它们需要在每次页面被调用时被初始化。

但在启动时,我收到以下消息:

原因:java.lang.IllegalStateException: No thread-bound request 发现:您指的是实际之外的请求属性吗? Web 请求,或处理原始请求之外的请求 接收线程?如果您实际上是在 Web 请求中操作 仍然收到此消息,您的代码可能在外面运行 DispatcherServlet/DispatcherPortlet:在这种情况下,使用 RequestContextListener 或 RequestContextFilter 暴露当前 请求。

如果 Spring 尝试在启动时实例化我的 Module bean,并且由于 bean 是范围请求,它不能这样做(上下文请求未实例化)

如果我删除事件管理,一切正常。

所以,我的问题是:

是否可以让事件监听器成为范围请求?以及如何做到这一点?

谢谢

【问题讨论】:

    标签: spring event-handling


    【解决方案1】:

    尝试在 Singleton ApplicationListener 中注入作用域代理来处理 TestEvent。

    @Scope(proxyMode=ScopedProxyMode.TARGET_CLASS, value="request")
    public class TestEventHandler {
    
        public void onTestEvent(TestEvent event) 
            // ...  
        }
    
    }
      public class TestEventApplicationListener implements ApplicationListener<TestEvent> {
    
        @Autowired
        private TestEventHandler handler;
    
        @Override
        public void onApplicationEvent(TestEvent event) {
    
            handler.onTestEvent(event);
    
        }
    }
    

    【讨论】:

    • 我不能这样做,因为 Spring 在每次调用“getModule”方法时都会提供一个新实例,而每个请求都没有一个实例。是请求代理的问题
    • 由于您的事件处理程序不直接实现 ApplicationListener 并通过组合(自 3.0 以来已过滤)获取事件,您的初始问题已解决。由于您的事件处理程序现在是一个 aop 范围的代理,因此可以将其注入到单例 bean 中。见static.springsource.org/spring/docs/current/…
    猜你喜欢
    • 2011-09-22
    • 2013-01-21
    • 1970-01-01
    • 2011-08-15
    • 1970-01-01
    • 2011-08-19
    • 1970-01-01
    • 2011-09-06
    • 1970-01-01
    相关资源
    最近更新 更多