问题:此注入的依赖项将始终从SimpleController
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();
}
}
答案 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");
}
}