Spring 靜態工廠方式創建對象(菜鳥3)

實例對象
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Car {
    private  int id;
    private String name;
}
工廠創建
public class CarFactory {
    private static Map<Integer ,Car> carMap;
    static {
        carMap=new HashMap<Integer, Car>();
        carMap.put(10001,new Car(10001,"寶馬"));
        carMap.put(10002,new Car(10002,"奔馳"));

    }
    public static  Car getCar(Integer id){
        return carMap.get(id);
    }

}

配置xml

<bean id="car" class="com.yk.factory.CarFactory" factory-method="getCar">
    <constructor-arg value="10001"></constructor-arg>
</bean>

調用

ApplicationContext applicationContext=new ClassPathXmlApplicationContext("springfactory.xml");
Car car=(Car) applicationContext.getBean("car");
System.out.println(car);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章