spring源码附录(4)FactoryBean的使用

一、FactoryBean接口

public interface FactoryBean {

    T getObject() throws Exception;

    Class getObjectType();

    default boolean isSingleton() {
        return true;
    }

}
  • getObject:返回FactoryBean创建的Bean实例,如果isSingleton返回true,则该实例会放到Spring容器的单例缓存池中。
  • isSingleton:返回由FactoryBean创建的bean实例的作用域是singleton还是prototype。
  • getObjectType:返回FactoryBean创建的类型。

二、例子

/**
 * 
 * @author dqf
 * @since 5.0
 */
public class Car {
    private int maxSpeed;
    private String brand;
    private double price;

    public int getMaxSpeed() {
        return maxSpeed;
    }

    public void setMaxSpeed(int maxSpeed) {
        this.maxSpeed = maxSpeed;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}
/**
 * 
 * @author dqf
 * @since 5.0
 */
public class CarFactoryBean implements FactoryBean{

    private String carInfo;

    @Override
    public Car getObject() throws Exception {
        Car car = new Car();
        String[] infos = carInfo.split(",");
        car.setBrand(infos[0]);
        car.setMaxSpeed(Integer.valueOf(infos[1]));
        car.setPrice(Double.valueOf(infos[2]));
        return car;
    }

    @Override
    public Class getObjectType() {
        return Car.class;
    }


    public String getCarInfo() {
        return carInfo;
    }


    public void setCarInfo(String carInfo) {
        this.carInfo = carInfo;
    }

}
<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.demo4.CarFactoryBean">
        <property name="carInfo">
            <value>超级跑车,400,2000000value>
        property>
    bean>


beans>
public class Test {
    public static void main(String[] args) {
        BeanFactory bf = new XmlBeanFactory(new ClassPathResource("springContext.xml"));
        Car car = (Car)bf.getBean("car");
        System.out.println(car.getBrand()+","+car.getMaxSpeed()+","+car.getPrice());

        CarFactoryBean carFactory = (CarFactoryBean)bf.getBean("&car");
        System.out.println(carFactory.getCarInfo());
    }
}

这里写图片描述

你可能感兴趣的:(spring源码,spring源码分析)