接口 BeanFactory 和 ApplicationContext 都是用来从容器中获取 Spring beans 的,可是,他们两者有很大不一样java
我看到过不少问 BeanFactory 和 ApplicationContext 不一样点的问题,考虑到这,我应该使用前者仍是后者从 Spring 容器中获取 beans 呢?请向下看
面试
这是一个很是简单而又很复杂的问题,一般来讲,Spring beans 就是被 Spring 容器所管理的 Java 对象,来看一个简单的例子spring
package com.zoltanraffai; public class HelloWorld { private String message; public void setMessage(String message){ this.message = message; } public void getMessage(){ System.out.println("My Message : " + message); } }
在基于 XML 的配置中, beans.xml 为 Spring 容器管理 bean 提供元数据app
Spring 容器负责实例化,配置和装配 Spring beans,下面来看如何为 IoC 容器配置咱们的 HelloWorld POJOthis
<?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id = "helloWorld" class = "com.zoltanraffai.HelloWorld"> <property name = "message" value = "Hello World!"/> </bean> </beans>
如今,它已经被 Spring 容器管理了,接下来的问题是:咱们怎样获取它?翻译
这是一个用来访问 Spring 容器的 root 接口,要访问 Spring 容器,咱们将使用 Spring 依赖注入功能,使用 BeanFactory 接口和它的子接口
特性:3d
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 是 Spring 应用程序中的中央接口,用于向应用程序提供配置信息
它继承了 BeanFactory 接口,因此 ApplicationContext 包含 BeanFactory 的全部功能以及更多功能!它的主要功能是支持大型的业务应用的建立
特性:code
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 的全部特性,一般推荐使用前者。可是也有一些限制情形,好比移动应用内存消耗比较严苛,在那些情景中,使用更轻量级的 BeanFactory 是更合理的。然而,在大多数企业级的应用中,ApplicationContext 是你的首选。xml
翻译自:Difference Between BeanFactory and ApplicationContext in Spring对象