为啥要使用FactoryBean:
在配置Bean的时候,需要用到IOC容器中的其它Bean,这个时候使用FactoryBean配置最合适。
public class Car {
private String brand;
private double price; public Car() {
System.out.println("com.cn.Car's Constructor");
} public Car(String brand, double price) {
this.brand = brand;
this.price = price;
} public void setBrand(String brand) {
System.out.println("setBrand");
this.brand = brand;
} public String getBrand() {
return brand;
} public void setPrice(double price) {
this.price = price;
} public double getPrice() {
return price;
} @Override
public String toString() {
return "Car{" +
"brand='" + brand + '\'' +
", price=" + price +
'}';
}
}
/**
* 自定义的FactoryBean需要实现FactoryBean接口
*/
public class CarFactoryBean implements FactoryBean<Car>{
//FactoryBean自己的属性
private String brand; public void setBrand(String brand) {
this.brand = brand;
} //返回bean的对象
@Override
public Car getObject() throws Exception {
return new Car("BMW", 500000);
} @Override
public Class<?> getObjectType() {
return Car.class;
} @Override
public boolean isSingleton() {
return true;
}
}
<?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">
<!--
通过FactoryBean来配置Bean的实例
class:指向FactoryBean的全类名
property:配置FactoryBean的属性
但实际返回的实例是FactoryBean的getObject()方法返回的实例
-->
<bean id="car" class="factorybean.CarFactoryBean">
<property name="brand" value="BMW"></property>
</bean>
</beans>
public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("12-1.xml");
Car car = (Car) ctx.getBean("car");
System.out.println(car);
}
}
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOIAAAAnCAIAAACdVwOHAAADaElEQVR4nO2ZsY7UMBCG73V2UiEEFRKcdO7oTteuWwQPMOIhmJKOinkJbOleDQonjhPbu9lLlqzh/3RF5HUc2/NlbOfu3r2/f/X6Tfx7enrqMn5/+RQvZn+zOmlJrfBGIPrw/Pn44y0N149fifbuFChzd6mmZ8tzj29T067rHj8eY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