Problem: This injected dependency will always return 0 from SimpleController
- Why does the context get lost for this bean when trying to do dependency injection into an HttpSessionListener implementation?
- What is principles behind this am I missing/confusing for this not to be working?
- How do I fix this?
Project on Github webApp project Source
Consider the following:
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>
Service: SessionService
@Service
public class SessionService{
private int counter = 0;
public SessionService(){}
public void addOne(){
coutner++;
}
public void removeOne(){
counter--;
}
public int getTotalSessions(){
return counter;
}
}
Controller: SimpleController
@Component
public SimpleController
{
@Autowired
private SessionService sessionService;
@RequestMapping(value="/webAppStatus")
@ResponseBody
public String getWebAppStatus()
{
return "Number of sessions: "+sessionService.getTotalSessions();
}
}