【问题标题】:Accessing Spring Session scoped Proxy Beans访问 Spring Session 范围的代理 Bean
【发布时间】:2011-02-18 10:01:41
【问题描述】:

我正在使用带有 Spring 3 后端的 Struts 2 开发 Web 应用程序。我正在使用 Spring aop:proxy bean 来处理我的会话 bean,而不是 Struts 2 SessionAware 接口。一切正常,直到我有一个在 Struts ExecAndWait 拦截器下运行的动作。因为这个拦截器实际上是在一个单独的线程下运行我的操作,所以当我尝试访问我的代理会话 bean 时,我得到一个 BeanCreationException/IllegalStateException。在这种情况下,我是否可以使用另一种“弹簧方式”来获取会话 bean?

问候

【问题讨论】:

  • 当然,当您的子线程需要访问 bean 时,会话可能已被用户销毁。可能需要通过重新审视范围来处理。

标签: java spring struts2 javabeans


【解决方案1】:

来自Execute and Wait Interceptor 文档

重要提示:因为动作将在单独的线程中运行,所以不能使用 ActionContext,因为它是 ThreadLocal。这意味着如果您需要访问例如会话数据,您需要实现 SessionAware 而不是调用 ActionContext.getSession()。

会话范围 bean 的问题在于它们依赖于由 RequestContextListenerRequestContextFilter 设置的线程本地属性。但后者允许你设置非常有趣的threadContextInheritable 标志...

如果您的ExecAndWait 拦截器为每个它服务的请求创建新线程,则可继承的本地线程应该将会话范围的 bean 传播到子线程。但是,如果 Struts 使用线程池(更可能的是,我已经很久没有使用 Struts2)来处理这个请求,这将产生非常意外和危险的结果。你可以试试这个标志,也许它会成功。

【讨论】:

    【解决方案2】:

    您可以使用 Spring 实现自己的 ExecAndWait 拦截器。您还可以将此操作的管理/创建委托给 Spring。后面的详细信息在 S2 spring 插件文档中。

    【讨论】:

      【解决方案3】:

      您可以使用 ,RequestContextHolder(Holder 类以线程绑定的 RequestAttributes 对象的形式公开 Web 请求。)使会话范围的代理 bean 可用于子线程。

      定义一个自定义的 ExecuteAndWait 拦截器并在 doIntercept 方法中使用 RequestContextHolder 中的以下静态方法

      public static void setRequestAttributes(RequestAttributes attributes,布尔可继承)

      将给定的 RequestAttributes 绑定到当前线程。

      参数: attributes - 要公开的 RequestAttributes,或 null 以重置线程绑定上下文 inheritable - 是否将 RequestAttributes 公开为子线程可继承(使用 InheritableThreadLocal)

      示例代码

      public class CustomExecuteAndWaitInterceptor extends ExecuteAndWaitInterceptor {
      
          @Override
          protected String doIntercept(ActionInvocation actionInvocation) throws Exception {
               RequestAttributes requestAtteiAttributes = RequestContextHolder.getRequestAttributes(); //Return the RequestAttributes currently bound to the thread. 
               RequestContextHolder.setRequestAttributes(requestAtteiAttributes, true);
             //do something else if you want ..
              return super.doIntercept(actionInvocation);
      
          }   
      }
      

      【讨论】:

        猜你喜欢
        • 2017-05-13
        • 1970-01-01
        • 1970-01-01
        • 2012-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-11
        • 1970-01-01
        相关资源
        最近更新 更多