2009-12-23 105 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