I want to inject currentUser instance in HomeController class. so for every request, HomeController will have currentUser object.
My configuration:
<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>
But I am getting following error.
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)
What is the problem? and Is there any better/simple alternative?
Cheers.
With scoped-proxies, Spring still needs to know the type of the bean when the context is initialized, and in this case it’s failing to do so. You need to try and give it more information.
I notice that you’re only specifying
factory-beanin your definition ofcurrentUser, with nofactory-methodspecified. I’m actually rather surprised that that’s a valid definition, since the two are normally used together. So try adding thefactory-methodattribute tocurrentUser, which specifies the method onuserProviderFactoryBeanwhich creates the user bean. That method needs to have a return type of yourUserclass, which Spring will use to infer the type ofcurrentUser.Edit: OK, after your comment below, it seems you’ve misunderstood how to use factory beans in Spring. When you have a bean of type
FactoryBean, you don’t need to use thefactory-beanattribute as well. So instead of this:You just need this:
Here,
UserProvideris aFactoryBean, and Spring knows how to handle that. The end result will be that thecurrentUserbean will be whateverUserProvidergenerates, rather than an instance ofUserProvideritself.The
factory-beanattribute is used when the factory is not aFactoryBeanimplementation, but just a POJO, and it allows you to tell Spring explicitly how to use the factory. But because you’re usingFactoryBean, there’s no need for this attribute.