How to inject dependencies into HttpSessionListener, using Spring and without calls, like context.getBean("foo-bar")
?
Dependency Injection is a fundamental aspect of the Spring framework, through which the Spring container “injects” objects into other objects or “dependencies”. Simply put, this allows for loose coupling of components and moves the responsibility of managing components onto the container.
@Autowired annotation is used to let Spring know that autowiring is required. This can be applied to field, constructor and methods. This annotation allows us to implement constructor-based, field-based or method-based dependency injection in our components.
Since 2003, Dependency Injection has been a core feature of the Spring framework. The source code can be found here.
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
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); } ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With