先从SpringBean提及,Spring Beans是被Spring容器管理的Java对象,好比:spring
public class HelloWorld { private String message; public void setMessage(String message){ this.message = message; } public void getMessage(){ System.out.println("My Message : " + message); } }
咱们通常经过Application.xml配置Spring Bean元数据。性能
<?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 Bean被Spring容器管理以后,能够在程序中获取使用它了。this
BeanFactory是Spring容器的基础接口,提供了基础的容器访问能力。code
BeanFactory提供懒加载方式,只有经过getBean方法调用获取Bean才会进行实例化。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继承自BeanFactory接口,ApplicationContext包含了BeanFactory中全部的功能。继承
具备本身独特的特性:接口
ApplicationContext采用的是预加载,每一个Bean都在ApplicationContext启动后实例化。get
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。大多数企业应用中Application是你的首选。it