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?