关于如何在Listener中注入service和ServletContextListener源码分析

    今天在做项目时突然发现我该如何向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");
    }
}

 

posted @ 2016-09-24 21:01  1234ztc  阅读(5477)  评论(0编辑  收藏  举报