1. 程式人生 > >Spring配置bean之靜態工廠方法

Spring配置bean之靜態工廠方法

通過靜態工廠方法配置bean

  1. 首先建立car類,設定brand,price兩個屬性
public class Car {
    
    private String brand;
    private int price;

    public String getBrand() {
        return brand;
    }

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

    public int getPrice() {
        return price;
    }

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

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

    public Car() {
        System.out.println("car's constructor...");

    }

    public Car(String brand, int price) {
        super();
        this.brand = brand;
        this.price = price;
    }
  1. 再建立StaticCarFactory類
public class StaticCarFactory {

    private static Map<String, Car> cars = new HashMap<String, Car>();

    static {
        cars.put("audi", new Car("audi", 3000000));
        cars.put("ford", new Car("ford", 4000000));
    }

    //靜態工廠方法
    public static Car getCar(String name) {

        return cars.get(name);

    }
  1. 在建立beans-factory.xml配置bean 在這裡插入圖片描述
  2. 最後在主函式中建立容器,輸出就可以啦!在這裡插入圖片描述