我想在 HomeController 类中注入(inject) 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 的类型,而在这种情况下它无法做到这一点。你需要尝试给它更多的信息。
我注意到您在 currentUser
的定义中只指定了 factory-bean
,没有指定 factory-method
。我真的很惊讶这是一个有效的定义,因为这两者通常一起使用。因此,尝试将 factory-method
属性添加到 currentUser
,它指定 userProviderFactoryBean
上创建用户 bean 的方法。该方法需要有一个 User
类的返回类型,Spring 将使用它来推断 currentUser
的类型。
编辑: 好吧,在你下面的评论之后,你似乎误解了如何在 Spring 中使用工厂 bean。当你有一个 FactoryBean
类型的 bean 时,你也不需要使用 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
,所以不需要此属性。
关于java - 使用 AOP 的 Spring session 范围 bean 中的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1951259/