本文介绍了HttpSessionListener实现内部的依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Problem: This injected dependency will always return 0 from SimpleController

  1. 为什么在尝试将依赖项注入到HttpSessionListener实现中时,此bean的上下文会丢失?
  2. 这背后的原理是什么?我想让它不起作用吗?
  3. 我该如何解决?

Github上的项目 webApp项目源

Project on 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();
  }

}

推荐答案

在web.xml中像这样声明<listener>

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

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

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

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.

对此有解决方法.还有更多.

请注意,

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

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

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

这篇关于HttpSessionListener实现内部的依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 09:38