我想在 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)
问题是什么?有没有更好/简单的替代方案?
Cheers.
对于范围代理,Spring 在初始化上下文时仍然需要知道 bean 的类型,在这种情况下它无法做到这一点。您需要尝试为其提供更多信息。
我注意到你只是指定factory-bean
在你的定义中currentUser
, 没有factory-method
指定的。事实上,我很惊讶这是一个有效的定义,因为两者通常一起使用。所以尝试添加factory-method
归因于currentUser
,它指定了方法userProviderFactoryBean
它创建用户 bean。该方法需要有一个返回类型User
类,Spring 将使用它来推断类型currentUser
.
Edit:好的,在您发表下面的评论之后,看来您误解了如何在 Spring 中使用工厂 bean。当你有一个 type 的 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>
Here, UserProvider
is a FactoryBean
,Spring 知道如何处理这个问题。最终的结果将是currentUser
豆子将是任何UserProvider
生成,而不是一个实例UserProvider
itself.
The factory-bean
当工厂不是工厂时使用属性FactoryBean
实现,但只是一个 POJO,它允许您明确地告诉 Spring 如何使用工厂。但因为你正在使用FactoryBean
,不需要这个属性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)