spring – HttpSessionListener实现中的依赖注入
作者:互联网
问题:这个注入的依赖项将始终从SimpleController返回0
>为什么在尝试将依赖注入到HttpSessionListener实现中时,上下文会丢失?
>这背后的原则是什么,我错过/混淆这个不能工作?
>我该如何解决这个问题?
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();
}
}
解决方法:
声明< listener>时在web.xml中就像这样
<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中的有效条目.我不知道这是否是你的副本错误.
标签:spring,dependency-injection,servlets,web-applications,web-xml 来源: https://codeday.me/bug/20191007/1866203.html