Статический класс для получения сессионного компонента в Spring и JSF - PullRequest
1 голос
/ 15 января 2012

Мне нужен сессионный компонент, доступный для уровней обслуживания и доступа к данным, но я не хочу внедрять его в каждый объект.

Мне не нужно это:

 <!-- 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>

можно создать статический класс для получения сессионного компонента текущего запроса?

Примерно так:

 <!-- 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")
  }

}

Ответы [ 2 ]

2 голосов
/ 15 января 2012

Я не уверен, что это работает, и у меня нет способа попробовать это прямо сейчас, но как насчет этого:

public static UserPreferences getUserPreferences(){

    return (UserPreferences) ContextLoader.getCurrentWebapplicationContext()
                                            .getBean("userPreferences");
}
1 голос
/ 13 июля 2012

Определить вспомогательный класс, например 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 каждый раз, и выполнение метода будет делегировано сессионному компоненту.

public void test() {
     UserPreferences userPrefs = UserPrefHelper.getUserPrefs();
    //That's all. Don't worry about static access and thread safety. Spring is clever enough.                      
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...