簡體   English   中英

訪問Spring會話范圍的代理Bean

[英]Accessing Spring Session scoped Proxy Beans

我正在使用帶有Spring 3后端的Struts 2開發一個Web應用程序。 我正在使用Spring aop:代理bean來處理我的會話bean而不是Struts 2 SessionAware接口。 一切都工作正常,直到我有一個在Struts ExecAndWait攔截器下運行的Action。 因為這個攔截器實際上是在一個單獨的線程下運行我的動作,當我來嘗試訪問我的代理會話bean時,我得到一個BeanCreationException / IllegalStateException。 在這種情況下,是否還有另一種“彈簧方式”可以抓住我的會話bean?

問候

來自Execute和Wait Interceptor文檔

重要說明 :因為操作將在單獨的線程中運行,所以不能使用ActionContext,因為它是ThreadLocal。 這意味着如果您需要訪問(例如)會話數據,則需要實現SessionAware而不是調用ActionContext.getSession()。

會話范圍bean的問題在於它們依賴於RequestContextListenerRequestContextFilter設置的線程局部屬性。 但后者允許你設置非常有趣的threadContextInheritable標志...

如果您的ExecAndWait攔截器根據它所服務的每個請求創建新線程, ExecAndWait繼承的線程本地應該將會話范圍的bean傳播到子線程。 但是,如果Struts使用線程池(更可能的是,我沒有使用Struts2多年)來提供這些請求,這將產生非常意外和危險的結果。 你可以嘗試這個標志,也許它會做到這一點。

您可以使用RequestContextHolder (Holder類以線程綁定的RequestAttributes對象的形式公開Web請求。),以使子線程可以使用會話范圍的代理bean。

定義一個自定義的ExecuteAndWait攔截器,並在doIntercept方法中使用RequestContextHolder中的以下靜態方法

public static void setRequestAttributes(RequestAttributes attributes, boolean inheritable

將給定的RequestAttributes綁定到當前線程。

參數:attributes - 要公開的RequestAttributes,或者為null以重置可繼承的線程綁定上下文- 是否將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);

    }   
}

您可以使用Spring實現自己的ExecAndWait攔截器。 您還可以將此操作的管理/創建委派給Spring。 稍后詳細介紹了S2 spring插件文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM