<!-- 經過靜態工廠 -->
<bean
id="factory"
class="com.beanfactory.Factory"
factory-method="getCar">
<constructor-arg value="Audi"></constructor-arg>
</bean>java
package com.beanfactory;測試
import java.util.HashMap;
import java.util.Map;spa
public class Factory {
private static Map<String,Car> carMap = new HashMap<String,Car>();
static{
carMap.put("Audi", new Car("Audi",300000));
carMap.put("BMW", new Car("BMW",500000));
}
public static Car getCar(String carName){
return carMap.get(carName);
}
}xml
<!-- 經過實例方法 -->
<bean id="beanFactory" class="com.beanfactory.Instance"></bean>
<bean id="car2" factory-bean="beanFactory" factory-method="getCar">
<constructor-arg value="BMW"></constructor-arg>
</bean>get
package com.beanfactory;io
import java.util.HashMap;
import java.util.Map;class
public class Instance {
private Map<String,Car> carMap=null;import
public Instance() {
carMap = new HashMap<String,Car>();
carMap.put("Audi", new Car("Audi",300000));
carMap.put("BMW", new Car("BMW",500000));
}
public Car getCar(String carName){
return carMap.get(carName);
}
}方法
測試方法im
public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beanFactory.xml");
Car car = (Car) ctx.getBean("factory");
System.out.println(car);
Car car2 = (Car) ctx.getBean("car2");
System.out.println(car2);
}
}
控制檯結果: