【发布时间】:2014-10-11 19:16:18
【问题描述】:
我在 spring 中尝试使用会话范围 bean 时遇到错误,错误是:
HTTP Status 500 - Error creating bean with name 'scopedTarget.usuarioAutenticado': 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.
我的配置是: web.xml:
<servlet>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
WEB-INF/applicationContext*.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<url-pattern>/sys/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
还有豆子:
<bean id="usuarioAutenticado" class="com.wi.security.UsuarioAutenticado" scope="session">
<aop:scoped-proxy/>
</bean>
我一直在搜索这个问题,我发现的只是将以下行添加到 web.xml:
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
这解决了问题,但副作用是我所有的@Scheduled 注解的方法都运行了两次,我认为这是因为 spring 正在创建两个上下文。
阅读 Spring 文档说:
DispatcherServlet、RequestContextListener 和 RequestContextFilter 都做到了 同样的事情,即将 HTTP 请求对象绑定到为该请求提供服务的线程。这 使请求和会话范围的 bean 在调用链的下游可用。
所以,我不明白为什么不只使用 DispatcherServlet 配置。 希望有人可以帮助我找到解决方案,我是春天的新手。 提前致谢。
【问题讨论】:
标签: java spring spring-mvc