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?
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.
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.
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 ... }
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