// Car.java
package com.baobaotao.beanfactory;
public class Car {
private String brand;
private String color;
private int maxSpeed;
public Car() {
}
public void introduce() {
System.out.println("brand:" + brand + "; color:" + color + "; maxSpeed:"
+ maxSpeed);
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getMaxSpeed() {
return maxSpeed;
}
public void setMaxSpeed(int maxSpeed) {
this.maxSpeed = maxSpeed;
}
}
// beans.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="car" class="com.baobaotao.beanfactory.Car">
<property name="brand" value="红旗CA72"></property>
<property name="color" value="黑色"></property>
<property name="maxSpeed" value="200"></property>
</bean>
</beans>
// BeanFactoryTest.java
package com.baobaotao.beanfactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class BeanFactoryTest {
public static void main(String[] args) throws Throwable {
Resource res = new ClassPathResource(
"com/baobaotao/beanfactory/beans.xml");
BeanFactory bf = new XmlBeanFactory(res);
Car car = (Car) bf.getBean("car");
car.introduce();
}
}
Spring用Resource接口表示一个来源无关的资源。这里,我们使用Resource表示Spring配置文件。XmlBeanFactory通过Resource装载Spring配置信息并启动IoC容器,然后就可以能过BeanFactory#getBean(beanName)方法从IoC容器中获取Bean了。通过BeanFactory启动IoC容器时,并不会初始化配置文件中定义的Bean,初始化动作发生在第一个调用时。对于单实例(singleton)的Bean来说,BeanFactory会缓存Bean实例,所以第二次使用getBean()获取Bean时将直接从IoC容器的缓存中获取Bean实例。