Spring配置bean之靜態工廠方法
阿新 • • 發佈:2018-12-21
通過靜態工廠方法配置bean
- 首先建立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; }
- 再建立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); }
- 在建立beans-factory.xml配置bean
- 最後在主函式中建立容器,輸出就可以啦!