Spring 中有两种类型的 bean , 一种是普通的 bean , 另一种是工厂 bean , 即 FactroyBean。
工厂 bean 跟普通 bean 不同 , 其返回的对象不是指定类的一个实例 , 其返回的是该工厂 bean 的 getObject 方法所返回的对象。
<?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.xsd"> <bean id="car" class="com.itdjx.spring.factorybeans.CarFactoryBean">
<property name="name" value="BMW"/>
</bean> </beans>
package com.itdjx.spring.factorybeans; /**
* @author Wáng Chéng Dá
* @create 2017-03-03 8:08
*/
public class Car { private String name; private int price; public int getPrice() {
return price;
} public void setPrice(int price) {
this.price = price;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Car(String name, int price) {
this.name = name;
this.price = price;
} @Override
public String toString() {
return "Car{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
}
package com.itdjx.spring.factorybeans; import org.springframework.beans.factory.FactoryBean; /**
* @author Wáng Chéng Dá
* @create 2017-03-03 8:10
*/
public class CarFactoryBean implements FactoryBean { private String name; public void setName(String name) {
this.name = name;
} @Override //factoryBean 返回的实例
public Object getObject() throws Exception {
System.out.println("I am CarFactoryBean's getObject method...");
return new Car(name, 500000);
} @Override //factoryBean 返回的类型
public Class<?> getObjectType() {
System.out.println("I am CarFactoryBean's getObjectType method...");
return Car.class;
} @Override //返回的实例是否为单例
public boolean isSingleton() {
System.out.println("I am CarFactoryBean's isSingleton method...");
return true;
}
}
package com.itdjx.spring.factorybeans; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; /**
* @author Wáng Chéng Dá
* @create 2017-03-03 8:14
*/
public class Main { public static void main(String[] args) { ApplicationContext cxt = new ClassPathXmlApplicationContext("factory-beans.xml");
Car car = (Car) cxt.getBean("car");
System.out.println(car); }
}
控制台输出:
I am CarFactoryBean's isSingleton method... |
创建 IOC 容器时调用 isSingleton 若是返回 true 调用 getObjectType , 若返回 false , IOC 直接创建完成。
创建 Car 实例时调用 isSingleton -->> getObject , 实例创建完成。