spring destroy-method +请求范围bean

时间:2011-04-12 16:26:24

标签: spring spring-mvc

所以我想做这样的事情:

@Component
@Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)
public class MyBean {
    @Autowired HttpServletRequest request;

    @PreDestroy 
    public void afterRequest() {
        try {
            System.out.println("After request...");
            // use request here:
        }
        finally {
            System.out.println("Completed successfully...");
        }
    }
}

在“成功完成...”消息日志之后,我最终收到以下消息:

  

09:19:16 WARN对名为'scopedTarget.myBean'的bean调用destroy方法失败:java.lang.IllegalStateException:找不到线程绑定请求:您是指实际Web请求之外的请求属性,或处理原始接收线程之外的请求?如果您实际上是在Web请求中操作并仍然收到此消息,则您的代码可能在DispatcherServlet / DispatcherPortlet之外运行:在这种情况下,请使用RequestContextListener或RequestContextFilter来公开当前请求。

我不确定该怎么做,因为我的日志记录表明destroy方法已成功完成。有谁知道发生了什么事?

编辑: 这是mvc-servlet.xml。正如你所看到的,这里并没有多少事情发生。它是所有注释驱动的:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/mvc
   http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
   http://www.springframework.org/schema/util
   http://www.springframework.org/schema/util/spring-util-2.0.xsd">

<!-- properties file -->
<context:property-placeholder location="app.properties" />

<context:component-scan base-package="my.package.web" />
<context:component-scan base-package="my.package.services" />

<mvc:annotation-driven />

<bean class="org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:viewClass="org.springframework.web.servlet.view.JstlView" p:prefix="/WEB-INF/view" p:suffix=".jspx" />
</beans>

2 个答案:

答案 0 :(得分:0)

如果你使用没有spring MVC的请求范围,你应该在web-app listener中声明org.springframework.web.context.request.RequestContextListener

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

检查http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-scopes-other-web-configuration

答案 1 :(得分:0)

我从来没有让这个工作,但我最终更改代码以在控制器方法上应用@After建议,这具有相同的效果。