2012-01-15 62 views
1

我需要一個會話bean可訪問服務和數據訪問層,但我不想將它注入到每個對象中。在Spring和JSF中檢索會話bean的靜態類

我不希望這樣的:

<!-- a HTTP Session-scoped bean exposed as a proxy --> 
    <bean id="userPreferences" class="com.foo.UserPreferences" scope="session"> 

      <!-- this next element effects the proxying of the surrounding bean --> 
      <aop:scoped-proxy/> 
    </bean> 

    <!-- a singleton-scoped bean injected with a proxy to the above bean --> 
    <bean id="userService" class="com.foo.SimpleUserService"> 

     <!-- a reference to the proxied 'userPreferences' bean --> 
     <property name="userPreferences" ref="userPreferences"/> 

    </bean> 

它是更多鈔票來創建一個靜態類用於檢索當前請求的會話bean?

事情是這樣的:

<!-- a HTTP Session-scoped bean exposed as a proxy --> 
     <bean id="userPreferences" class="com.foo.UserPreferences" scope="session"> 

       <!-- this next element effects the proxying of the surrounding bean --> 
       <aop:scoped-proxy/> 
     </bean> 

Public Class sessionResolver{ 

    public static UserPreferences getUserPreferences(){ 

    //Not real code!!! 
    return (UserPreferences)WebApplicationContex.getBean("userPreferences") 
    } 

} 
+0

我把模擬代碼放在getUserPreferences中,因爲我認爲它不能在春季配置中完成,但我更喜歡使用配置代替代碼。 – jlvaquero 2012-01-15 11:33:53

回答

2

我不知道這工作,我也沒有辦法去嘗試它的權利,但這個怎麼樣:

public static UserPreferences getUserPreferences(){ 

    return (UserPreferences) ContextLoader.getCurrentWebapplicationContext() 
              .getBean("userPreferences"); 
} 
+0

我會試試看。謝謝!至少,我現在知道如何從任何我的代碼中檢索webApplicationContext。 XD – jlvaquero 2012-01-15 11:30:47

+0

@ user551263但我認爲它可能不適用於請求或會話範圍。我認爲這些範圍僅適用於網絡控制器。但值得一試。 – 2012-01-16 08:35:44

+1

看起來像是有效的。 – jlvaquero 2012-01-17 15:55:07

1

定義助手類如UserPrefHelper.java

public class UserPrefHelper { 
    private static com.foo.UserPreferences userPrefs; 
    private void setUserPrefs(com.foo.UserPreferences userPrefs) { 
    this.userPrefs = userPrefs; 
    } 
    private static UserPreferences getUserPrefs() { 
    return userPrefs; 
    } 
} 



<!-- a HTTP Session-scoped bean exposed as a proxy --> 
<bean id="userPreferences" class="com.foo.UserPreferences" scope="session"> 

     <!-- this next element effects the proxying of the surrounding bean --> 
     <aop:scoped-proxy/> 
</bean> 

<!-- a singleton-scoped bean injected with a proxy to the above bean --> 
<bean id="userPrefHelper" class="com.foo.UserPrefHelper"> 

    <!-- a reference to the proxied 'userPreferences' bean --> 
    <property name="userPreferences" ref="userPreferences"/> 

</bean> 

然後在您的類中直接使用該輔助類,就這些了。它會每次將您變爲代理的UserPreferences對象,並將方法執行委託給會話範圍的bean。

public void test() { 
    UserPreferences userPrefs = UserPrefHelper.getUserPrefs(); 
    //That's all. Don't worry about static access and thread safety. Spring is clever enough.      
}