Spring的IoC容器就是一个实现了BeanFactory接口的可实例化类。事实上,Spring提供了两种不同的容器:一种是最基本的BeanFactory,另一种是扩展的ApplicationContext。BeanFactory 仅提供了最基本的依赖注入支持,而 ApplicationContext 则扩展了BeanFactory ,提供了更多的额外功能。实例化这两种容器时是有区别的:
(1)BeanFactory
public class BeanFactoryTest { public static void main(String[] args) throws Throwable{ ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource res = resolver.getResource("classpath:com/baobaotao/beanfactory/beans.xml"); System.out.println(res.getURL()); BeanFactory bf = new XmlBeanFactory(res); System.out.println("init BeanFactory."); Car car = bf.getBean("car",Car.class); System.out.println("car bean is ready for use!"); car.introduce(); } }
(2)ApplicationContext
public class XmlApplicationContextTest { public static void main(String[] args) {
//如果配置文件放置在类路径下,用户可以优先使用ClassPathXmlApplicationContext实现类 ApplicationContext ctx = new ClassPathXmlApplicationContext("com/baobaotao/context/*.xml"); Car car1 = ctx.getBean("car",Car.class);
//如果配置文件放置在文件系统的路径下,则可以优先考虑使用FileSystemXmlApplicationContext实现类 // ctx = new FileSystemXmlApplicationContext("D:/masterSpring/chapter3/src/com/baobaotao/context/*.xml"); // Car car2 = ctx.getBean("car",Car.class); } }
ApplicationContext的初始化和BeanFactory有一个重大的区别:BeanFactory在初始化容器时,并未实例化Bean,直到第一次访问某个Bean时才实例目标Bean;而ApplicationContext则在初始化应用上下文时就实例化所有的单实例的Bean。因此ApplicationContext的初始化时间会比BeanFactory稍长一些.