2009-12-23 102 views
3

我想在HomeController类中注入currentUser实例。所以对于每一个请求,HomeController都会有currentUser对象。问题Spring会话范围bean与AOP

我的配置:

<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) 

什么问题?有没有更好的/简单的选择?

干杯。

+0

给你的工厂bean代码 – Bozho 2009-12-23 08:03:55

回答

4

对于scoped-proxies,Spring在初始化上下文时仍然需要知道bean的类型,在这种情况下,它没有这样做。您需要尝试并提供更多信息。

我注意到您只在currentUser的定义中指定了factory-bean,没有指定factory-method。实际上我很惊讶那是一个有效的定义,因为两者通常一起使用。因此,请尝试将factory-method属性添加到currentUser,该属性指定创建用户Bean的userProviderFactoryBean上的方法。该方法需要您的User类的返回类型,Spring将使用该类来推断currentUser的类型。


编辑: OK,下面您的评论之后,看来你误解了如何用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> 

这里,UserProviderFactoryBean,以及Spring知道如何来处理这个问题。最终结果将是currentUser bean将生成任何UserProvider,而不是UserProvider本身的实例。

factory-bean属性用于工厂不是FactoryBean的实现,而只是一个POJO,它允许您明确告诉Spring如何使用工厂。但是因为您使用的是FactoryBean,所以不需要此属性。

+0

UserProvider类实现Spring的FactoryBean接口。所以它已经实现了方法public Object getObject(); public Class getObjectType(); public boolean isSingleton();.所以这就是为什么我没有指定工厂方法 – Nachiket 2009-12-24 06:02:11

+0

啊,愚蠢的错误..但谢谢你让我清楚。 :) – Nachiket 2009-12-24 11:53:22