BeanFactory接口
用来访问spring容器的root接口。要访问spring容器,需使用spring依赖注入功能,使用BeanFactory接口和它的子接口
特性:
◆Bean的实例化和串联
通常,BeanFactory的实现是使用懒加载的方式,意味着beans只有在我们通过getBean()方法直接调用它们时才进行实例化。实现BeanFactory最常用的api是XMLBeanFactory
package com.zoltanraffai;
import org.springframework.core.io.ClassPathResource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.xml.XmlBeanFactory;
public class HelloWorldApp{
public static void main(String[] args) {
XmlBeanFactory factory = new XmlBeanFactory (new ClassPathResource("beans.xml"));
HelloWorld obj = (HelloWorld) factory.getBean("helloWorld");
obj.getMessage();
}
}
ApplicationContext接口
ApplicationContext是spring应用程序中的中央接口,用于向应用程序提供配置信息。它继承了BeanFactory接口,保含BeanFactory的所有功能以及更多功能。主要功能是支持大型业务应用的创建。
特性:
◆Bean initantiation/wiring
◆Bean的实例化/串联
◆自动的beanpostprocessor注册
◆自动beanfactorypostprocessor注册
◆方便的MessageSource访问(i18n)
◆ApplicationEvent的发布
ApplicationContext是预加载,所以每个bean都在ApplicationContext启动后实例化。
package com.zoltanraffai;
import org.springframework.core.io.ClassPathResource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.xml.XmlBeanFactory;
public class HelloWorldApp{
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();
}
}
总结
ApplicationContext包含BeanFactory的所有特性,通常推荐使用ApplicationContext。但也有一些限制情形,例如移动应用内存消耗比较严苛,使用轻量级的BeanFactory更合理。然而在大多数企业及应用中,ApplicationContext是你的首选。