How to inject dependencies into HttpSessionListener, using Spring and without calls, like context.getBean("foo-bar")
?
Asked
Active
Viewed 2.4k times
26

Eyal
- 3,412
- 1
- 44
- 60

Illarion Kovalchuk
- 5,774
- 8
- 42
- 54
3 Answers
30
Since the Servlet 3.0 ServletContext has an "addListener" method, instead of adding your listener in your web.xml file you could add through code like so:
@Component
public class MyHttpSessionListener implements javax.servlet.http.HttpSessionListener, ApplicationContextAware {
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (applicationContext instanceof WebApplicationContext) {
((WebApplicationContext) applicationContext).getServletContext().addListener(this);
} else {
//Either throw an exception or fail gracefully, up to you
throw new RuntimeException("Must be inside a web application context");
}
}
}
which means you can inject normally into the "MyHttpSessionListener" and with this, simply the presence of the bean in your application context will cause the listener to be registered with the container
-
So by this approach, can you then completely remove 'MyHttpSessionListener' from your
section from within your web.xml? – stackoverflow Dec 10 '13 at 13:50 -
1Yes, that is correct. You do not even need a web.xml with this approach. – Yinzara Mar 05 '14 at 00:58
-
In Spring 5.x you don't need to ApplicationContextAware interface. The @component is registering the Listener just fine as it seems. – Petros Makris Sep 05 '18 at 05:38
8
You can declare your HttpSessionListener
as a bean in Spring context, and register a delegation proxy as an actual listener in web.xml
, something like this:
public class DelegationListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent se) {
ApplicationContext context =
WebApplicationContextUtils.getWebApplicationContext(
se.getSession().getServletContext()
);
HttpSessionListener target =
context.getBean("myListener", HttpSessionListener.class);
target.sessionCreated(se);
}
...
}

axtavt
- 239,438
- 41
- 511
- 482
-
That's fine solution, I wonder why there's no such DelegationListener in Spring itself. – Illarion Kovalchuk Mar 12 '10 at 19:13
-
One reason why this doesn't work as well as with DelegatingFilterProxy is that there is no way to pass it a parameter from the web.xml. You end up having to assume a bean name and then you can only ever support a single DelegationListener (unless there's a way around that I'm not seeing). – Nick Spacek Mar 12 '12 at 12:59
-
1
With Spring 4.0 but also works with 3, I implemented the example detailed below, listening to ApplicationListener<InteractiveAuthenticationSuccessEvent>
and injecting the HttpSession
https://stackoverflow.com/a/19795352/2213375