同一個 Action 類中,execute() 能正常使用注入的 loginService,但 sessionDestroyed() 卻為 null。原因:HttpSessionListener 由 Servlet 容器實例化,非 Spring 管理,故依賴注入失效。
public void sessionDestroyed(HttpSessionEvent event) {
WebApplicationContext ctx = WebApplicationContextUtils
.getWebApplicationContext(event.getSession().getServletContext());
LoginService service = ctx.getBean(LoginService.class);
service.updateIsFirstLogin(...);
}
org.springframework.web.context.request.HttpSessionListener 並註冊為 Bean,Spring 會自動注入。WebApplicationContextUtils 從 ServletContext 取得 Spring 容器再手動查找。