Spring会话范围bean与AOP中的问题
问题内容:
我想在HomeController类中注入currentUser实例。因此,对于每个请求,HomeController将具有currentUser对象。
我的配置:
<bean id="homeController" class="com.xxxxx.actions.HomeController">
<property name="serviceExecutor" ref="serviceExecutorApi"/>
<property name="currentUser" ref="currentUser"/>
</bean>
<bean id="userProviderFactoryBean" class="com.xxxxx.UserProvider">
<property name="userDao" ref="userDao"/>
</bean>
<bean id="currentUser" factory-bean="userProviderFactoryBean" scope="session">
<aop:scoped-proxy/>
</bean>
但是我得到以下错误。
Caused by: java.lang.IllegalStateException: Cannot create scoped proxy for bean 'scopedTarget.currentUser': Target type could not be determined at the time of proxy creation.
at org.springframework.aop.scope.ScopedProxyFactoryBean.setBeanFactory(ScopedProxyFactoryBean.java:94)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1350)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:540)
问题是什么?有没有更好/简单的选择?
干杯。
问题答案:
对于作用域代理,Spring在初始化上下文时仍需要知道Bean的类型,在这种情况下,它无法这样做。您需要尝试并提供更多信息。
我注意到您只是factory-bean
在的定义中指定currentUser
,未factory- method
指定。实际上,我很惊讶这是一个有效的定义,因为两者通常一起使用。因此,请尝试将factory- method
属性添加到中currentUser
,以指定userProviderFactoryBean
创建用户bean的方法。该方法需要具有您的User
类的返回类型,Spring会使用该返回类型来推断的类型currentUser
。
编辑:
确定,在下面的评论之后,您似乎误解了如何在Spring中使用工厂bean。当您拥有类型的Bean时FactoryBean
,您也不需要使用该factory- bean
属性。所以代替这个:
<bean id="userProviderFactoryBean" class="com.xxxxx.UserProvider">
<property name="userDao" ref="userDao"/>
</bean>
<bean id="currentUser" factory-bean="userProviderFactoryBean" scope="session">
<aop:scoped-proxy/>
</bean>
您只需要这个:
<bean id="currentUser" class="com.xxxxx.UserProvider" scope="session">
<aop:scoped-proxy/>
<property name="userDao" ref="userDao"/>
</bean>
这UserProvider
是一个FactoryBean
,Spring知道如何处理。最终结果将是currentUser
bean将是UserProvider
生成的任何东西,而不是其UserProvider
自身的实例。
该factory- bean
属性在工厂不是FactoryBean
实现而是POJO的情况下使用,它使您可以明确地告诉Spring如何使用工厂。但是因为您正在使用FactoryBean
,所以不需要此属性。