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

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

 

 

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

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

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

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

看下面两个demo对象

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

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();
        
    }
相关文章
相关标签/搜索