Spring学习笔记十---FactoryBean

FactoryBean
实现FactoryBean接口

<?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">

    <!-- class指向factoryBean的全类名
    property设置factoryBean的属性
    返回时FactoryBean的getObject方法
    -->
    <bean id="car" class="fb.CarFactoryBean">
        <property name="brand" value="BMW"></property>
    </bean>
</beans>
package fb;

import org.springframework.beans.factory.FactoryBean;

public class CarFactoryBean implements FactoryBean<Car>{

    private String brand;

    public CarFactoryBean() {

    }

    public CarFactoryBean(String brand) {
        this.brand = brand;
    }

    public String getBrand(){
        return this.brand;
    }


    public void setBrand(String name) {
        this.brand = name;
    }
    //返回bean的实例
    @Override
    public Car getObject() throws Exception {
        return new Car(this.brand, 200000);
    }

    //返回bean的class
    @Override
    public Class<?> getObjectType() {
        return Car.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
package fb;

public class Car {
    private String brand;
    private double price;

    public Car() {
    }

    public Car(String brand, double price) {
        this.brand = brand;
        this.price = price;
    }

    public String getBrand() {
        return brand;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

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


    @Override
    public String toString() {
        return "Car{" +
                "brand='" + brand + '\'' +
                ", price=" + price +
                '}';
    }
}
package fb;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class Main {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("fb//FactoryBean.xml");
        Car car = (Car)ctx.getBean("car");
        System.out.println(car);
    }
}


你可能感兴趣的:(Spring学习笔记十---FactoryBean)