12.Spring通过FactoryBean配置Bean

为啥要使用FactoryBean

  在配置Bean的时候,需要用到IOC容器中的其它Bean,这个时候使用FactoryBean配置最合适。

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

    public Car() {
        System.out.println("com.cn.Car's Constructor");
    }

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

    public void setBrand(String brand) {
        System.out.println("setBrand");
        this.brand = brand;
    }

    public String getBrand() {
        return brand;
    }

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

    public double getPrice() {
        return price;
    }

    @Override
    public String toString() {
        return "Car{" +
                "brand='" + brand + '\'' +
                ", price=" + price +
                '}';
    }
}
/**
 * 自定义的FactoryBean需要实现FactoryBean接口
 */
public class CarFactoryBean implements FactoryBean<Car>{

  //FactoryBean自己的属性
private String brand; public void setBrand(String brand) { this.brand = brand; } //返回bean的对象 @Override public Car getObject() throws Exception { return new Car("BMW", 500000); } @Override public Class<?> getObjectType() { return Car.class; } @Override public boolean isSingleton() { return true; } }
<?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">
       <!--
       通过FactoryBean来配置Bean的实例
       class:指向FactoryBean的全类名
       property:配置FactoryBean的属性
       但实际返回的实例是FactoryBean的getObject()方法返回的实例
       -->
       <bean id="car" class="factorybean.CarFactoryBean">
              <property name="brand" value="BMW"></property>
       </bean>
</beans>
public class Main {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("12-1.xml");
        Car car = (Car) ctx.getBean("car");
        System.out.println(car);
    }
}

posted on 2015-06-19 11:18  jec  阅读(161)  评论(0编辑  收藏  举报

导航