HttpSessionListener实现中的依赖注入

时间:2013-12-09 17:26:26

标签: spring servlets web-applications dependency-injection web.xml

问题:此注入的依赖项将始终从SimpleController

返回0
  1. 为什么在尝试将依赖注入到HttpSessionListener实现中时,这个bean的上下文会丢失?
  2. 这背后的原则是什么,我错过/混淆了这个不能工作?
  3. 我该如何解决这个问题?
  4. Github上的项目webApp project Source

    请考虑以下事项:

    SessionCounterListener

    public class SessionCounterListener implements HttpSessionListener {
    
      @Autowired
      private SessionService sessionService;
    
      @Override
      public void sessionCreated(HttpSessionEvent arg0) {
        sessionService.addOne();
      }
    
      @Override
      public void sessionDestroyed(HttpSessionEvent arg0) {
        sessionService.removeOne();
      } 
    }
    

    web.xml

    <web-app ...>
        <listener>
            <listener-class>com.stuff.morestuff.SessionCounterListener</listener-class>
        </listener>
    
    </web-app>
    

    的applicationContext.xml

    <xml ...>
    
       <!-- Scan for my SessionService & assume it has been setup correctly by spring-->
       <context:component-scan base-package="com.stuff"/>
    
    </beans>
    

    服务: SessionService

    @Service
    public class SessionService{
    
      private int counter = 0;
    
      public SessionService(){}
    
      public void addOne(){
        coutner++;
      }
    
      public void removeOne(){
        counter--;
      }
    
      public int getTotalSessions(){
         return counter;
      }
    
    }
    

    控制器: SimpleController

    @Component
    public SimpleController
    {
      @Autowired
      private SessionService sessionService;
    
      @RequestMapping(value="/webAppStatus")
      @ResponseBody
      public String getWebAppStatus()
      {
         return "Number of sessions: "+sessionService.getTotalSessions();
      }
    
    }
    

2 个答案:

答案 0 :(得分:3)

在web.xml中声明<listener>时,如此

<listener>
    <listener-class>com.stuff.morestuff.SessionCounterListener</listener-class>
</listener>

您告诉 Servlet容器实例化listener-class元素中指定的类。换句话说,Spring不会管理此实例,因此无法注入任何内容,字段将保持为null

这有workarounds。并some more

注意这个

<!-- Scan for my SessionService & assume it has been setup correctly by spring-->
<context:component-scan base-package="com.stuff"/>

不是web.xml中的有效条目。我不知道这是否是你的复制错误。

答案 1 :(得分:0)

这是显示实际解决方案的答案。

您应该像这样修改 SessionCountListener ,以上示例将起作用:

public class SessionCounterListener implements HttpSessionListener {

  @Autowired
  private SessionService sessionService;

  @Override
  public void sessionCreated(HttpSessionEvent arg0) {
    getSessionService(se).addOne();
  }

  @Override
  public void sessionDestroyed(HttpSessionEvent arg0) {
    getSessionService(se).removeOne();
  }

  private SessionService getSessionService(HttpSessionEvent se) {
    WebApplicationContext context = 
      WebApplicationContextUtils.getWebApplicationContext(
        se.getSession().getServletContext());
    return (SessionService) context.getBean("sessionService");
  } 
}