工厂方法配置bean
1:静态工厂方法配置bean
1):对象
package com.spring.helloworld; public class Car { private String name; private double jia; public void setName(String name) { this.name = name; } public void setJia(double jia) { this.jia = jia; } @Override public String toString() { return "Car [name=" + name + ", jia=" + jia + "]"; } public Car(String name, int jia) { super(); this.name = name; this.jia = jia; } }
2):静态工厂方法
package com.spring.helloworld; import java.util.HashMap; import java.util.Map; public class StaticCarFactory { private static Map<String ,Car> cars=new HashMap<String,Car>(); static{ cars.put("audi", new Car("audi",30000)); cars.put("ford", new Car("ford",40000)); } public static Car getCar(String name){ return cars.get(name); } }
3):配置文件
<!--
class属性:指向静态工厂方法的全类名
factory-method:指向静态工厂方法的名称
constructor-arg:如果工厂方法需要传入参数,则使用构造器配置参数
-->
<bean id="car" class="com.spring.helloworld.StaticCarFactory"
factory-method="getCar">
<constructor-arg value="ford"></constructor-arg>
</bean>
2:实例工厂方法
package com.spring.helloworld; import java.util.HashMap; import java.util.Map; public class InstanceCarFactory { private Map<String ,Car> cars=null; public InstanceCarFactory(){ cars=new HashMap<String,Car>(); cars.put("audi", new Car("audi",30000)); cars.put("ford", new Car("ford",30000)); } public Car getCar(String name){ return cars.get(name); } }
<!-- 配置工厂的实例 --> <bean id="carFactory" class="com.spring.helloworld.InstanceCarFactory"></bean> <!-- 通过实例工厂方法来配置bean factory-bean:指向实例工厂方法的全类名 factory-method:指向静态工厂方法的名字 constructor-arg:如果工厂方法需要传入参数,则使用构造器配置参数 --> <bean id="car" factory-bean="carFactory" factory-method="getCar"> <constructor-arg value="ford"></constructor-arg> </bean>