Spring 自动连接请求范围bean的方法
我只是想知道是否有其他方法可以自动连接请求范围的bean。所以现在我在配置文件中创建了一个Spring 自动连接请求范围bean的方法,spring,spring-boot,autowired,Spring,Spring Boot,Autowired,我只是想知道是否有其他方法可以自动连接请求范围的bean。所以现在我在配置文件中创建了一个bean: @Bean @Scope(value=WebApplicationContext.SCOPE_REQUEST, proxyMode=ScopedProxyMode.DEFAULT) public List<String> stringBean(){ return new ArrayList<String>(); } 这完全行得通。但我不喜欢自动连接上下文和演员阵
bean
:
@Bean
@Scope(value=WebApplicationContext.SCOPE_REQUEST, proxyMode=ScopedProxyMode.DEFAULT)
public List<String> stringBean(){
return new ArrayList<String>();
}
这完全行得通。但我不喜欢自动连接上下文和演员阵容的需要。所以我尝试直接自动连接bean:
@Autowired
private List<String> stringBean;
是否有其他方法自动连接请求范围的bean?ScopedProxyMode。默认值
,如果尚未配置,则表示否(未创建代理)。尝试使用ScopedProxyMode.TARGET\u CLASS
以使用CGLIB
代理
正如您已经知道的,单例bean只创建一次,它们的依赖项注入在初始化时进行。正如您在问题中所说,对于请求范围的bean,该bean在该点不存在,您会得到异常
为了避免这种情况,您需要让Spring知道您想要使用代理bean。代理bean只是一个由Spring动态创建的bean,它公开了与目标相同的公共接口。这个代理bean是Spring将要注入到您的bean中的一个,当调用它的方法时,它将把调用委托给为该请求创建的真正的代理bean
有两种代理机制:JDK动态代理
,当使用接口时(ScopedProxyMode.interfaces
)或CGLIB
(ScopedProxyMode.TARGET\u CLASS
)
我希望你能明白
查看一些有用的文档:
ScopedProxyMode。默认值
,如果您没有配置任何,则表示否(未创建代理)。尝试使用ScopedProxyMode.TARGET\u CLASS
以使用CGLIB
代理。@alcope看起来这是可行的。你能解释一下区别吗?也可以是答案。当然,你有。这都是关于代理的。
@Autowired
private List<String> stringBean;
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'stringBean': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.