@Autowired in ServletContextListener

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

    As others have said this listener observes by the web servlet(tomcat) context (Not the Spring Container) and is notified of servlet startup/shutdown.

    Since it is created by the servlet outside of the Spring container it is not managed by Spring hence @Autowire members is not possible.

    If you setup your bean as a managed @Component then Spring will create the instance and the listener wont register with the external servlet.

    You cannot have it both ways..

    One solution is the remove the Spring annotations and manually retrieve your member from the Spring Application context and set your members that way.

    ie

        public class InitApp implements ServletContextListener {
    
            private ConfigrationService weatherConfService;
    
            private static ApplicationContext   applicationContext  = new ClassPathXmlApplicationContext("classpath:web-context.xml");
    
            @Override
            public void contextInitialized(ServletContextEvent servletContextEvent) {
                weatherConfService = applicationContext.getBean(ConfigrationService.class);
                System.out.println(weatherConfService);
            }
    
            @Override
            public void contextDestroyed(ServletContextEvent servletContextEvent) {
            }
        }
    

提交回复
热议问题