Spring - Injecting a dependency into a ServletContextListener

前端 未结 4 1007
心在旅途
心在旅途 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
        ...
    }    
    
    0 讨论(0)
  • 2020-11-27 17:40

    You cant have spring to do that, as already stated that is created by the server. If you need to pass params to your listener, you can define it in your web xml as a context-param

    <context-param> 
            <param-name>parameterName</param-name>
            <param-value>parameterValue</param-value>
        </context-param>
    

    And in the Listener you can retrieve it like below;

     event.getServletContext().getInitParameter("parameterName")
    

    Edit 1:

    See the link below for another possible solution:

    How to inject dependencies into HttpSessionListener, using Spring?

    0 讨论(0)
  • 2020-11-27 17:44

    I resolved this by removing the listener bean and creating a new bean for my properties. I then used the following in my listener, to get the properties bean:

    @Override
    public void contextInitialized(ServletContextEvent event) {
    
        final WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
        final Properties props = (Properties)springContext.getBean("myProps");
    }
    
    0 讨论(0)
  • 2020-11-27 17:47

    As mentioned before the ServletContextListener is created by the server and so it is not managed by spring.

    If you wish to be notified of the ServletContext, you can implement the interface:

    org.springframework.web.context.ServletContextAware
    
    0 讨论(0)
提交回复
热议问题