Spring中的 BeanFactory和 ApplicationContext的区别与解释

Spring中的 BeanFactory和 ApplicationContext的区别与解释

 

 

BeanFactory :这是一个工厂,用于生成任意bean。

           采取延迟加载第一次getBean时才会初始化Bean。

ApplicationContext:是BeanFactory的子接口,功能更强大。(国际化处理、事件传递、Bean自动装配、各种不同应用层的Context实现)。

    当配置文件被加载,就进行对象实例化。

看下面两个demo

下面这个是当配置文件被加载,对象就已经实例化了

public void demo01(){
        //从spring容器获得
        String xmlPath = "com/itheima/b_di/beans.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
       BookService bookService
= (BookService) applicationContext.getBean("bookServiceId"); bookService.addBook(); }

 

这个就是延迟加载的例子

public void demo02(){
        //使用BeanFactory  --第一次调用getBean实例化
        String xmlPath = "com/itheima/b_di/beans.xml";
        
        BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(xmlPath));
        
        BookService bookService = (BookService) beanFactory.getBean("bookServiceId");
        
        bookService.addBook();
        
    }

 

posted on 2017-03-09 16:04  Hennessy_Road  阅读(313)  评论(0编辑  收藏  举报