自动发送请求范围bean的方法

时间:2017-05-30 11:10:39

标签: spring spring-boot autowired

我只是想知道是否有其他方法来自动装配请求范围的bean。所以现在我在配置文件中创建了一个bean

@Bean
@Scope(value=WebApplicationContext.SCOPE_REQUEST, proxyMode=ScopedProxyMode.DEFAULT)
public List<String> stringBean(){
    return new ArrayList<String>();
}

通常情况下,我会自动将applicationContext用于bean

@Autowired
private ApplicationContext context; 

@Override
public void anyName() {
    List<String> list = (List<String>) getContext().getBean("stringBean");
}

这完全没问题。但我不喜欢自动上传背景和演员的需要。所以我试着直接自动装豆:

@Autowired
private List<String> stringBean;

我通过启动应用程序获得了一个异常,因为在启动请求之前不会创建bean。

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.

是否有其他方法可以自动发送请求范围的bean?

1 个答案:

答案 0 :(得分:5)

ScopedProxyMode.DEFAULT,如果您尚未配置任何,则表示NO(未创建代理)。尝试使用ScopedProxyMode.TARGET_CLASS以使用CGLIB代理

正如您所知,单例bean只创建一次,并且它们的依赖注入是在初始化时进行的。正如你在你的问题中所说的那样,对于请求范围内的bean,那时bean不存在并且你得到了异常。

为避免这种情况,您需要让Spring知道您要使用代理bean。代理bean只是一个由Spring动态创建的bean,它暴露了与您所针对的公共接口相同的公共接口。这个代理bean是一个Spring将要注入你的bean,并且在调用它的方法时会将调用委托给为该请求创建的真实调用。

使用接口(JDK dynamic proxies)或ScopedProxyMode.INTERFACESCGLIB)时,有两种代理机制:ScopedProxyMode.TARGET_CLASS

我希望你明白这一点。

查看一些有用的文档:

Scoped beans as dependencies

Choosing the type of proxy to create

Proxying mechanisms

Aspect Oriented Programming with Spring

相关问题