FactoryBean
Spring中有两种类型的Bean,一种是普通Bean,另一种是工厂Bean,即FactoryBean。工厂Bean跟普通Bean不同,其返回的对象不是指定类的一个实例,其返回的是该工厂Bean的getObject方法所返回的对象。
Spring的配置文件
<!--通过FactoryBean获取bean-->
<bean id="car3" class="com.an.factory.FactoryBean">
<constructor-arg name="brand" value="BMW"/>
</bean>
FactoryBean的类
需要实现FactoryBean接口 重写三种方法 通过getObject方法得到对象实例bean
package com.an.factory;
import com.an.things.Car;
public class FactoryBean implements org.springframework.beans.factory.FactoryBean {
private String brand;
public void setBrand(String brand) {
this.brand = brand;
}
public FactoryBean(String brand) {
this.brand = brand;
}
@Override
public Car getObject() throws Exception {
return new Car(brand,"shanghai",5000.0);
}
@Override
public Class<?> getObjectType() {
return Car.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
Car 的类
package com.an.things;
public class Car {
private String brand;
private String corp;
private double price;
private int maxSpeed;
public Car(){
System.out.println("创建了一个汽车!");
}
public Car(String brand, String corp, double price) {
this.brand = brand;
this.corp = corp;
this.price = price;
}
public Car(String brand, String corp, int maxSpeed) {
this.brand = brand;
this.corp = corp;
this.maxSpeed = maxSpeed;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getCorp() {
return corp;
}
public void setCorp(String corp) {
this.corp = corp;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getMaxSpeed() {
return maxSpeed;
}
public void setMaxSpeed(int maxSpeed) {
this.maxSpeed = maxSpeed;
}
@Override
public String toString() {
return "Car{" +
"brand='" + brand + '\'' +
", corp='" + corp + '\'' +
", price=" + price +
", maxSpeed=" + maxSpeed +
'}';
}
}
主函数
package com.an.factory;
import com.an.things.Car;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
Car car3 = (Car)ctx.getBean("car3");
System.out.println(car3);
}
}
输出结果
Car{brand='BMW', corp='shanghai', price=5000.0, maxSpeed=0}