我需要一个可访问服务和数据访问层的会话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 :(得分:2)
我不确定这是否有效,我现在没有办法尝试,但是这个怎么样:
public static UserPreferences getUserPreferences(){
return (UserPreferences) ContextLoader.getCurrentWebapplicationContext()
.getBean("userPreferences");
}
答案 1 :(得分: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.
}