Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject dependencies into HttpSessionListener, using Spring?

How to inject dependencies into HttpSessionListener, using Spring and without calls, like context.getBean("foo-bar") ?

like image 780
Illarion Kovalchuk Avatar asked Mar 12 '10 14:03

Illarion Kovalchuk


People also ask

How is dependency injection done in Spring boot?

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.

Which annotation can be used for injecting dependencies in Spring?

@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.

Does Spring boot have dependency injection?

Since 2003, Dependency Injection has been a core feature of the Spring framework. The source code can be found here.


2 Answers

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

like image 93
Yinzara Avatar answered Sep 27 '22 20:09

Yinzara


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);     }      ... } 
like image 25
axtavt Avatar answered Sep 27 '22 20:09

axtavt