有时候采用编码的方式得到bean会更简单些。
CarBeanFactory.java
public class CarFactoryBean implements FactoryBean<Car> {
private String carInfo;
public String getCarInfo() {
return carInfo;
}
public void setCarInfo(String carInfo) {
this.carInfo = carInfo;
}
public Car getObject() throws Exception {
Car car = new Car();
String[] infos = carInfo.split(",");
car.setBrand(infos[0]);
car.setMaxSpeed(Integer.parseInt(infos[1]));
car.setPrice(Double.parseDouble(infos[2]));
return car;
}
public Class<Car> getObjectType() {
return Car.class;
}
public boolean isSingleton() {
return false;
}
}
配置文件要这样写:
<bean id="car1" class="com.baobaotao.fb.CarFactoryBean"
p:carInfo="红旗CA72,200,20000.00"/>
记得实现implements FactoryBean<T>接口,然后调用的时候,便会主动去找getObject()方法了,返回的是Bean,而不是这个Factory本身。
When you need to ask a container for an actual FactoryBean
instance itself instead of the bean it produces, preface the bean’s id with the ampersand symbol ( &
) when calling the getBean()
method of the ApplicationContext
. So for a given FactoryBean
with an id of myBean
, invoking getBean("myBean")
on the container returns the product of the FactoryBean
; whereas, invoking getBean("&myBean")
returns the FactoryBean
instance itself.