Dependency Injection inside of HttpSessionListener implementation

前端 未结 2 1954
余生分开走
余生分开走 2021-01-07 03:45

Problem: This injected dependency will always return 0 from SimpleController

  1. Why does the context get lost for this bean when try
相关标签:
2条回答
  • 2021-01-07 03:52

    This is an answer here that shows the actual solution.

    You should modify SessionCountListener like this, and the above example will work:

    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");
      } 
    }
    
    0 讨论(0)
  • 2021-01-07 04:12

    When you declare a <listener> in web.xml like so

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

    you are telling your Servlet container to instantiate the class specified in the listener-class element. In other words, this instance will not be managed by Spring and it will therefore not be able to inject anything and the field will remain null.

    There are workarounds to this. And some more.

    Note that this

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

    is not a valid entry in web.xml. I don't know if that was a copy mistake on your part.

    0 讨论(0)
提交回复
热议问题