先从SpringBean说起,Spring Beans是被Spring容器管理的Java对象,比如:
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容器管理之后,可以在程序中获取使用它了。
BeanFactory是Spring容器的基础接口,提供了基础的容器访问能力。
BeanFactory提供懒加载方式,只有通过getBean方法调用获取Bean才会进行实例化。
常用的是加载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启动后实例化。
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是你的首选。