使用AOP的Spring会话范围bean中的问题

我想在HomeController类中注入currentUser实例。 所以对于每个请求,HomeController都会有currentUser对象。

我的配置:

          

但我得到了以下错误。

 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属性。 所以不是这样的:

       

你只需要这个:

     

这里, UserProvider是一个FactoryBean ,Spring知道如何处理它。 最终结果是currentUser bean将是UserProvider生成的任何内容,而不是UserProvider本身的实例。

如果factory-bean不是FactoryBean实现,而是仅仅是POJO,则使用factory-bean属性,并且它允许您明确告诉Spring如何使用工厂。 但是因为你正在使用FactoryBean ,所以不需要这个属性。