//自定义的FactoryBean需要实现FactoryBean接口
public class CarFactoryBean implements FactoryBean<Car>{
private String brand;
public void setBrand(String brand) {
this.brand = brand;
}
//返回bean的对象
@Override
public Car getObject() throws Exception {
// TODO Auto-generated method stub
return new Car(brand, 600000);
}
@Override
public Class<?> getObjectType() {
// TODO Auto-generated method stub
return Car.class;
}
@Override
public boolean isSingleton() {
// TODO Auto-generated method stub
return true;
}
}
Main.java
public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-beanfactory.xml");
Car car =(Car) ctx.getBean("car");
System.out.println(car);
}
}
beans-beanfactory.xml配置
通过factoryBean 来配置Bean的实例
class:指向FactoryBean的全类名
property:配置FactoryBean的属性
但实际返回的实例确实FactoryBean的getObject()方法返回的实例!
<bean id="car" class="com.jhh.spring.beans.factorybean.CarFactoryBean">
<property name="brand" value="BMW"></property>
</bean>
运行结果
Car [brand=BMW, price=600000.0]