首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Spring 注入 Service 在 HttpSessionListener 中為 null 解決

     編輯:程式設計疑難解答

同一個 Action 類中,execute() 能正常使用注入的 loginService,但 sessionDestroyed() 卻為 null。原因:HttpSessionListener 由 Servlet 容器實例化,非 Spring 管理,故依賴注入失效。

解決方案

  1. 從 ApplicationContext 手動取得 Bean:
    public void sessionDestroyed(HttpSessionEvent event) {
        WebApplicationContext ctx = WebApplicationContextUtils
            .getWebApplicationContext(event.getSession().getServletContext());
        LoginService service = ctx.getBean(LoginService.class);
        service.updateIsFirstLogin(...);
    }
    
  2. 改用 Spring 的 HttpSessionListener 介面:實作 org.springframework.web.context.request.HttpSessionListener 並註冊為 Bean,Spring 會自動注入。
  3. 將邏輯移至 Filter 或 Spring Session 事件:避免直接實作 Servlet API Listener。

關鍵點

  • Servlet 容器建立的元件(Listener、Filter、Servlet)預設不受 Spring 管理。
  • 需透過 WebApplicationContextUtils 從 ServletContext 取得 Spring 容器再手動查找。
  • 或改用 Spring 提供的對應介面,讓 Spring 掌管生命週期。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved