2012-01-15 1 views
1

서비스 및 데이터 액세스 계층에 액세스 할 수있는 세션 빈이 필요하지만 모든 객체에 세션 빈을 삽입하고 싶지는 않습니다.Spring과 JSF의 세션 빈 검색에 대한 정적 클래스

나는 이것을 원하지 않는다 :

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

} 
+0

나는 스프링 구성에서 수행 할 수 없다고 생각하기 때문에 mock 코드를 getUserPreferences에 넣었지만 물론 코드 대신 구성을 선호합니다. – jlvaquero

답변

2

나는이 작품 확실하지 않다 나는 지금 그것을 시도 할 수있는 방법이 없지만 이것에 대해 어떻게 :

public static UserPreferences getUserPreferences(){ 

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

나는 그것을 시도 할 것이다. 감사! 적어도 이제는 내 코드의 anywere에서 webApplicationContext를 검색하는 방법을 알고 있습니다. XD – jlvaquero

+0

@ user551263하지만 요청 또는 세션 범위에서 작동하지 않을 것으로 생각됩니다. 나는이 범위가 웹 컨트롤러 내에서만 작동한다고 생각한다. 그러나 한번 시도해 볼 가치가 있습니다. –

+1

작동하는 것처럼 보입니다. – jlvaquero

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.      
} 
관련 문제