@Autowired in ServletContextListener

前端 未结 4 1614
一生所求
一生所求 2021-02-06 06:04

i hava aclass InitApp

@Component
public class InitApp implements ServletContextListener {

@Autowired
ConfigrationService weatherConfService;

/** Creates a new          


        
4条回答
  •  独厮守ぢ
    2021-02-06 06:44

    A couple of ideas came to me as I was having the same issue.

    First one is to use Spring utils to retrieve the bean from the Spring context within the listener:

    Ex:

    @WebListener
    public class CacheInitializationListener implements ServletContextListener {
    
        /**
         * Initialize the Cache Manager once the application has started
         */
        @Override
        public void contextInitialized(ServletContextEvent sce) {
            CacheManager cacheManager = WebApplicationContextUtils.getRequiredWebApplicationContext(
                    sce.getServletContext()).getBean(CacheManager.class);
            try {
                cacheManager.init();
            } catch (Exception e) {
                // rethrow as a runtime exception
                throw new IllegalStateException(e);
            }
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent sce) {
            // TODO Auto-generated method stub
    
        }
    }
    

    This works fine if you only have one or two beans. Otherwise it can get tedious. The other option is to explicitly call upon Spring's Autowire utilities:

    @WebListener
    public class CacheInitializationListener implements ServletContextListener {
    
        @Autowired
        private CacheManager cacheManager;
    
        /**
         * Initialize the Cache once the application has started
         */
        @Override
        public void contextInitialized(ServletContextEvent sce) {
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
            try {
                cacheManager.init();
            } catch (Exception e) {
                // rethrow as a runtime exception
                throw new IllegalStateException(e);
            }
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent sce) {
            // TODO Auto-generated method stub
    
        }
    }
    

    The caveat in both these solutions, is that the Spring context must by loaded first before either of these can work. Given that there is no way to define the Listener order using @WebListener, ensure that the Spring ContextLoaderListener is defined in web.xml to force it to be loaded first (listeners defined in the web descriptor are loaded prior to those defined by annotation).

提交回复
热议问题