Spring – Injecting a dependency into a ServletContextListener

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

Leave a Comment