Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - Injecting a dependency into a ServletContextListener

I would like to inject a dependency into a ServletContextListener. However, my approach is not working. I can see that Spring is calling my setter method, but later on when contextInitialized is called, the property is null.

Here is my set up:

The ServletContextListener:

public class MyListener implements ServletContextListener{      private String prop;      /* (non-Javadoc)      * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)      */     @Override     public void contextInitialized(ServletContextEvent event) {         System.out.println("Initialising listener...");         System.out.println(prop);     }      @Override     public void contextDestroyed(ServletContextEvent event) {     }      public void setProp(String val) {         System.out.println("set prop to " + prop);         prop = val;     } } 

web.xml: (this is the last listener in the file)

<listener>   <listener-class>MyListener</listener-class> </listener>  

applicationContext.xml:

<bean id="listener" class="MyListener">   <property name="prop" value="HELLO" /> </bean>   

Output:

set prop to HELLO Initialising listener... null 

What is the correct way to achieve this?

like image 282
dogbane Avatar asked Jan 20 '11 10:01

dogbane


People also ask

Does Spring have dependency injection?

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.

What is the difference between ServletContextEvent and ServletContextListener?

ServletContextEvent class provides alerts/notifications for changes to a web application's servlet context. ServletContextListener is a class that receives alerts/notifications about changes to the servlet context and acts on them.


1 Answers

The dogbane's answer (accepted) works but it makes testing difficult because of the way beans are instantiated. I prefere the approach suggested in this question :

@Autowired private Properties props;  @Override public void contextInitialized(ServletContextEvent sce) {     WebApplicationContextUtils         .getRequiredWebApplicationContext(sce.getServletContext())         .getAutowireCapableBeanFactory()         .autowireBean(this);      //Do something with props     ... }     
like image 144
a.b.d Avatar answered Sep 19 '22 14:09

a.b.d