dependency inject servlet listener

前端 未结 2 1981
情话喂你
情话喂你 2020-12-09 11:03

In my Stripes app I define the following class:

MyServletListener implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener {

  p         


        
相关标签:
2条回答
  • 2020-12-09 11:39

    Something like this should work:

    public class MyServletListener implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener {
        @Autowired
        private SomeService someService;        
        @Autowired
        private AnotherService anotherService; 
    
        public void contextInitialized(ServletContextEvent sce) {
            WebApplicationContextUtils
                .getRequiredWebApplicationContext(sce.getServletContext())
                .getAutowireCapableBeanFactory()
                .autowireBean(this);
        }
    
        ...
    }
    

    Your listener should be declared after Spring's ContextLoaderListener in web.xml.

    0 讨论(0)
  • 2020-12-09 11:58

    Little bit shorter and simpler is to use SpringBeanAutowiringSupport class.
    Than all you have to do is this:

    SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
    

    So using example from axtavt:

    public class MyServletListener implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener {
        @Autowired
        private SomeService someService;        
        @Autowired
        private AnotherService anotherService; 
    
        public void contextInitialized(ServletContextEvent sce) {
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
        }
    
        ...
    }
    
    0 讨论(0)
提交回复
热议问题