春季错误:“作用域'会话'对于当前线程无效;请考虑为此bean定义作用域代理”

时间:2019-01-02 20:33:28

标签: spring spring-boot spring-mvc

首先,我遵循了此线程中的建议: https://stackoverflow.com/a/26327870/1005607

我的GUI应用程序中有一个会话范围的bean。在应用程序内,还有一些Job进程(非GUI)可以在请求框架之外访问此bean。

春季版本: 4.1.5

定义是:

会话Bean类(请注意ScopedProxyMode)

@Component
@Scope(value="session", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class MyBean implements Serializable {
   //...
}

web.xml引用了RequestContextListener:

<listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener> 

作业在某些地方引用了会话bean,如下所示

@Autowired
private MyBean myBean; 

当非GUI作业访问此bean时,仍然出现错误:

    org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'scopedTarget.myBean': 
  Scope 'session' 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.
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:352)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    ...

0 个答案:

没有答案