spring_(12)通过 FactoryBean 配置Bean

为什么需要这个东西

因为我们有的时候在配置一个bean的时候,我们需要用到IOC容器里面的其他bean,这个时候通过FactoryBean去配置是最合适的

例子程序

基本结构

在这里插入图片描述

Car.java

package com.spring.beans.factorybean;

public class Car {

    private String brand;
    private double price;

    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;
    }

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

    @Override
    public String toString() {
        return "Car{" +
                "brand='" + brand + '\'' +
                ", price=" + price +
                '}';
    }
    public Car(String brand, double price){
        super();
        this.brand = brand;
        this.price = price;
    }
}

CarFactoryBean.java (需要实现FactoryBean接口)

package com.spring.beans.factorybean;

import org.springframework.beans.factory.FactoryBean;

//自定义的FactoryBean 需要实现FactoryBean接口
public class CarFactoryBean implements FactoryBean {

    private String brand;

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

    //返回bean 的对象
    @Override
    public Object getObject() throws Exception {
        return new Car(brand,500000);
    }

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

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

beans-beanfactory.xml

<?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="com.spring.beans.factorybean.CarFactoryBean">
        <property name="brand" value="BWM"></property>
    </bean>
</beans>

Main.java

package com.spring.beans.factorybean;

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

public class Main {

    public static void main(String[] args){

        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-beanfactory.xml");
        Car car = (Car) ctx.getBean("car");

        System.out.println(car);

    }
}

运行结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42036647/article/details/84205814