先從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