BeanFactory接口是spring IoC最核心的接口,是IoC的“大脑”,而ApplicationContext经过层层接口实现,最终也实现了BeanFactory接口,它在BeanFactory接口的基础上,添加了许多额外的功能,是Ioc的“躯体”。
关于2者的区别,先看在获取bean时2者有什么不同。
// xml配置:注意:Person1类是不存在的
<bean id="person" class="tzb.bean.life.cycle.Person1"/>
// 利用beanfactory获取bean
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
reader.loadBeanDefinitions(new FileSystemResource("C:\\JavaProject\\person.xml"));
System.out.println("利用beanfactory获取bean");
// System.out.println(factory.getBean("person").getClass().getName());
以上代码,如果注释掉最后一行打印,代码是可以正常执行的,去掉最后一行的注释后,程序会报错。
// xml配置:注意:Person1类是不存在的
<bean id="person" class="tzb.bean.life.cycle.Person1"/>
// ApplicationContext方式获取bean
ApplicationContext context1 = new FileSystemXmlApplicationContext("C:\\JavaProject\\person.xml");
而以上代码,则会直接报错。
也就是说,
BeanFacotry:是延迟加载,如果bean的注入有异常,BeanFacotry加载后,会在你第一次调用GetBean方法才会抛出异常;
ApplicationContext:在容器初始化的时候就加载并且检查,及时检查所有可能存在的异常。