java无法在会话超时时获取会话范围的bean
我需要在HttpSessionListener.sessionDestroyed()
上获得一个代理会话范围的bean。目标是在会话被破坏(通过invalidate()
或超时)时进行会话清理。我添加了ContextLoaderListener
来公开上下文,并通过WebApplicationContextUtils.getWebApplicationContext()
获得了bean
如果我自己在Servlet中使会话无效,那么一切都可以正常工作,但是当会话超时时,我会得到一个Scope 'session' is not active for the current thread;
。我知道清理工作是由Servlet引擎的内部线程完成的,但我仍然需要能够从HttpSessionListener
获取这个bean
我周围似乎有很多相同的问题,没有人找到解决方案,这就是为什么我要再次提问
我的应用程序上下文。xml没有bean声明,因为我使用的是注释
这是会话超时时我需要访问的bean:
@Component
@Scope(value="session", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class Access {
static private int SERIAL = 0;
private int serial;
public Access() {
serial = SERIAL++;
}
public int getSerial() {
return serial;
}
}
这是create
或destroy
手动启动会话的控制器
@Controller
public class Handler {
@Autowired
Access access;
@RequestMapping("/create")
public @ResponseBody String create() {
return "Created "+access.getSerial();
}
@RequestMapping("/destroy")
public @ResponseBody String destroy(HttpSession sess) {
int val = access.getSerial();
sess.invalidate();
return "Destroyed "+val;
}
}
这是收听会话销毁的HttpSessionListener,在这里我需要访问Access
会话范围bean的内容
public class SessionCleanup implements HttpSessionListener {
@Override
public void sessionDestroyed(HttpSessionEvent ev) {
// Get context exposed at ContextLoaderListener
WebApplicationContext ctx = WebApplicationContextUtils
.getWebApplicationContext(ev.getSession().getServletContext());
// Get the beans
Access v = (Access) ctx.getBean("access");
// prints a not-null object
System.out.println(v);
// this line raise the exception
System.out.println(v.getSerial());
}
@Override
public void sessionCreated(HttpSessionEvent ev) {/*Nothing to do*/}
}
下面的例外情况是在v.getSerial()
提出的
Ago 14, 2012 11:44:58 PM org.apache.catalina.session.StandardSession expire
SEVERE: Session event listener threw exception
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.access': 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:342)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:33)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.getTarget(Cglib2AopProxy.java:654)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:605)
at model.Access$$EnhancerByCGLIB$$438f41a5.toString(<generated>)
at java.lang.String.valueOf(String.java:2902)
at java.io.PrintStream.println(PrintStream.java:821)
at org.apache.tomcat.util.log.SystemLogHandler.println(SystemLogHandler.java:242)
at service.SessionCleanup.sessionDestroyed(SessionCleanup.java:24)
at org.apache.catalina.session.StandardSession.expire(StandardSession.java:709)
at org.apache.catalina.session.StandardSession.isValid(StandardSession.java:576)
at org.apache.catalina.session.ManagerBase.processExpires(ManagerBase.java:712)
at org.apache.catalina.session.ManagerBase.backgroundProcess(ManagerBase.java:697)
at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1364)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1649)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1658)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1658)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1638)
at java.lang.Thread.run(Thread.java:722)
Caused by: 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.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131)
at org.springframework.web.context.request.SessionScope.get(SessionScope.java:90)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:328)
... 19 more
最后,这里是我的网站。xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>session-listener-cleanup</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>service.SessionCleanup</listener-class>
</listener>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>1</session-timeout>
</session-config>
</web-app>
正如我所说,当我在控制器的方法destroy
中使会话无效时,一切都很顺利
更新1:找到可能的解决方案
出现这个问题是因为需要一个请求才能Spring访问会话bean。事件虽然我们有一个与线程关联的上下文,但没有请求
这里有一些可能的选择:
- 按照alexwen的建议,实现接口DisposableBean。这意味着将业务逻辑移动到模型对象 [here]李>
- 实施
DestructionAwareBeanPostProcessor
也由alexwen建议。这意味着在进行任何处理之前,您需要检查被处理的bean是否为Access
李> - 直接从会话中检索bean。这种方式不是很好,因为你使用了一种未记录的行为来实现结果,但确实有效 [here]李>
- 模拟servlet请求,并通过
RequestContextHolder
将其属性绑定到线程。这也会导致未记录的行为,在未来的版本中可能会被更改 [here]李>
我没有选择最后两个,因为它们没有记录。而且,我不喜欢在一颗特定的豆子之后清除每一颗豆子。由于我也不想将业务逻辑混合到我的模型bean中,所以我最终创建了一个@Service
来创建bean,并且还有一个destroy
方法
这个方法由访问bean的处理负责。我在Access
上实现了DisposableBean
接口,将AccessManager
服务注入Access
bean,并调用服务destroy
方法。服务如下所示:
@Service
public class AccessManager {
@Bean(name="access", destroyMethod="destroy")
@Scope(value="session", proxyMode=ScopedProxyMode.TARGET_CLASS)
@Autowired
public Access create(HttpServletRequest request) {
// creation logic
}
public void destroy(Access access) {
// disposal logic
}
}
# 1 楼答案
如果实现该接口,那么当会话被销毁时,访问类Spring上的DisposableBean将调用方法“destroy”
或者,您可以向Spring a DestructionAwareBeanPostProcessor注册,当会话作用域被销毁时,它将有机会处理会话作用域中的所有beanDocs and instructions here
如果你想知道Spring是如何做到这一切的,我建议你看看Spring在会话中注册为HttpSessionBindingListener的DisposableBeanAdapter