关于如何在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");
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM