【问题标题】:How to persist object on http request destroy in spring web 4.3如何在spring web 4.3中持久化http请求销毁对象
【发布时间】:2019-02-14 19:29:47
【问题描述】:

我有一个用大量数据表示用户状态的对象,并且这个对象可以在每个 http 请求中多次改变,所以我想使用的优化之一是仅在 http 请求销毁时保留这个对象。

问题是当我尝试在请求范围 bean 上使用 @PreDestroy 注释时,我不能使用请求范围依赖项,如 http 会话(例如调用 javax.servlet.http.HttpServletRequest#getSession()),因为 DispatcherServlet 重置了 org.springframework.web.servlet.FrameworkServlet#processRequest 中的所有请求范围 bean

            resetContextHolders(request, previousLocaleContext, previousAttributes);
            if (requestAttributes != null) {
                requestAttributes.requestCompleted();
            }

使用 PreDestroy 注释的方法通常用于释放它一直持有的资源,但是我想使用大量依赖项提交事务,这就是它不起作用的原因。

在 Servlet::doService 调用之后和请求范围 bean 重置之前,spring web 中有什么方法可以调用 bean 的方法吗?

【问题讨论】:

    标签: java spring spring-mvc


    【解决方案1】:

    您可以使用全球ServletContextListener。需要在bean级别注册回调,ServletContextListenercontext级别注册回调。

    public class MyServletContextListener
      implements ServletContextListener {
    
        @Override
        public void contextDestroyed(ServletContextEvent event) {
            System.out.println(
              "Executed callback ContextListener.");
        }
    
        @Override
        public void contextInitialized(ServletContextEvent event) {
            // Triggers when context initializes
        }
    }
    

    需要在配置类中注册到ServletListenerRegistrationBean

    @Bean
    ServletListenerRegistrationBean<ServletContextListener> servletListener() {
        ServletListenerRegistrationBean<ServletContextListener> srb
          = new ServletListenerRegistrationBean<>();
        srb.setListener(new MyServletContextListener());
        return srb;
    }
    

    【讨论】:

    • 我不明白Context 级别事件如何在org.springframework.web.context.request.RequestContextHolder#resetRequestAttributes 之前调用请求绑定bean。不幸的是,即使ServletRequestListener#requestDestroyed 也调用了RequestContextHolder#resetRequestAttributes
    猜你喜欢
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多