Spring容器中最常用的两个接口:BeanFactory和ApplicationContext。
ApplicationContext是BeanFactory的子接口,两个接口都可以实例化Spring容器。
BeanFactory和ApplicationContext的区别
- ApplicationContext默认初始化所有的singleton的Bean。
- ApplicationContext继承MessageSource,提供国际化支持。
- ApplicationContext继承ResourcePatternResolver,实现了资源访问。
- ApplicationContext继承ApplicationEventPublisher,事件发布机制。
- 可以同时加载多个资源文件。
ApplicationContext默认初始化所有的singleton的Bean
默认情况下使用ApplicationContext实例化Spring容器,Spring中的Bean为singleton。如果在初始化Bean配置错误,Spring会报错。而通过BeanFactory初始化Spring容器时,Bean配置错误,Spring不会报错,当实际通过getBean获取bean实例才会报错
ApplicationContext继承ResourcePatternResolver,实现了资源访问
ApplicationContext能实现资源的访问,是由于ResourcePatternResolver继承了
ResourceLoader接口。
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring.xml");
Resource resource = ac.getResource("classpath:a.txt");