Spring - Injecting a dependency into a ServletContextListener

前端 未结 4 1021
心在旅途
心在旅途 2020-11-27 16:59

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 l

4条回答
  •  失恋的感觉
    2020-11-27 17:31

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

提交回复
热议问题