您的位置:首页 > 移动开发

Spring中的beanFactory和ApplicationContext的有什么区别和关联

2015-03-10 10:58 274 查看


从上面的类结构图中可以看出来,ApplicationContext 是 BeanFactory接口的子接口

其中BeanFactory获得配置文件的实例是:

<span style="white-space:pre">	</span>// 使用BeanFactory 读取配置文件
BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
HelloService helloService4 = (HelloService) beanFactory.getBean("helloService");
helloService4.sayHello();


ApplicationContext获取配置文件实例的方法是:

<span style="white-space:pre">	</span>// 使用Spring Ioc 方式 获得HelloService 实例
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); // 获得工厂实例
HelloService helloService2 = (HelloService) applicationContext.getBean("helloService"); // 通过id获得实例
//helloService2.setInfo("itcast"); // 已经配置依赖注入
helloService2.sayHello();


其实两个在代码看来就是在获取配置文件的时候 的差异,他们还有其他的差异:

1)BeanFactory 采用的是延迟加载,第一次getBean的时候才会初始化Bean

2)ApplicationContext是对BeanFactory的扩展,提供了更多的功能

国际化处理
事件传递
Bean自动装配
各种不同应用层的Context实现

结论:开发中尽量使用ApplicationContext 就可以了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: