簡體   English   中英

Spring和JSF中檢索會話bean的靜態類

[英]Static class for retrieve session bean in Spring and 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")
  }

}

我不確定這是否有效,我現在沒有辦法嘗試,但是這個怎么樣:

public static UserPreferences getUserPreferences(){

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

定義一個輔助類,如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.                      
}

暫無
暫無

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

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