实例对象 @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);