@Autowired in ServletContextListener

前端 未结 4 1616
一生所求
一生所求 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:39

    By declaring

    
      com.web.Utils.InitApp
    
    

    in your web.xml, you're telling your container to initialize and register an instance of InitApp. As such, that object is not managed by Spring and you cannot @Autowired anything into it.

    If your application context is set up to component-scan the com.web.Utils package, then you will have a InitApp bean that isn't registered as a Listener with the container. So even though your other bean will be @Autowired, the servlet container won't ever hit it.

    That is the trade-off.

    There are workarounds to this if you use programmatic configuration with a ServletContainerInitializer or a WebApplicationInitializer for servlet 3.0. You wouldn't use @Autowired, you would just have setter/getter that you would use to set the instance.

    Here's an example

    class SpringExample implements WebApplicationInitializer {
        @Override
        public void onStartup(ServletContext servletContext) throws ServletException {
            WebApplicationContext context = ...;
    
            SomeBean someBean = context.getBean(SomeBean.class);
            CustomListener listener = new CustomListener();
            listener.setSomeBean(someBean);
    
            // register the listener instance
            servletContext.addListener(listener);
    
            // then register DispatcherServlet and ContextLoaderListener, as appropriate
            ...
        }
    }
    
    class CustomListener implements ServletContextListener {
        private SomeBean someBean;
    
        public SomeBean getSomeBean() {
            return someBean;
        }
    
        public void setSomeBean(SomeBean someBean) {
            this.someBean = someBean;
        }
    
        @Override
        public void contextInitialized(ServletContextEvent sce) {
           // do something with someBean
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent sce) {
        }
    }
    

    Note that Spring has some custom implementation of WebApplicationInitializer that are quite sophisticated. You really shouldn't need to implement it directly yourself. The idea remains the same, just deeper in the inheritance hierarchy.

提交回复
热议问题