今天在做項目時突然發現我該如何向listener中注入service對象,因為監聽器無法使用注解注入。
此時有人會想用以下代碼通過xml的方式注入:
ApplicationContext context=new ClassPathXmlApplication(*.xml); productService =(ProductService)context.getBean("productService");
這樣的話會導致一個問題,那就是Tomcat會兩次加載spring的配置文件。所以這種方式並不可取。
通過分析源碼我畫出了一張圖:
從上面的源碼我們可以看出其實spring的配置文件最終加載后就是放在ServletContext中。
所以我們可以直接從ServletContext中通過這個鍵取出配置文件,並注入productService。
public class InitDataListener implements ServletContextListener { ProductService productService=null; @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { } @Override public void contextInitialized(ServletContextEvent servletContextEvent) { //注入Service,直接到ServletContext中獲取Spring文件,但此方法不常用 // ApplicationContext context=(ApplicationContext) servletContextEvent.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); // productService=(ProductService) context.getBean("productService"); // System.out.println(productService); WebApplicationContext webApplicationContext= WebApplicationContextUtils.getWebApplicationContext(servletContextEvent.getServletContext()); productService=(ProductService) webApplicationContext.getBean("produtService"); } }