静态工厂方法
静态工厂类
package factory; import java.util.HashMap; import java.util.Map; /* * 静态工厂方法:直接调用某一个的静态方法就可以返回bean实例 */ public class StaticCarFactory { private static Map<String,Car> cars=new HashMap<String,Car>(); static { cars.put("aodi", new Car("aodi",3000)); cars.put("ford", new Car("ford",20000)); } //静态方法 public static Car getCar(String name) { return cars.get(name); } }
实体类
package factory; public class Car { private String brand; private int price; public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public String getBrand() { return brand; } public void setBrand(String brand) { System.out.println("setBrand..."); this.brand = brand; } public Car() { System.out.println("car Constructor..."); } public void init() { System.out.println("init..."); } public void destory() { System.out.println("destroy"); } public Car(String brand,int price) { this.brand=brand; this.price=price; } @Override public String toString() { return "Car [brand=" + brand + ", price=" + price + "]"; } }
配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"> <!-- 通过静态方法来配置bean,注意不是配置静态工厂实例方法 而是配置bean实例 --> <!-- class属性:指向静态工厂方法的全类名 factory-method:指向静态工厂方法的名字 constructor-arg:如果工厂方法需要传入参数,则使用constructor-arg来配置参数 --> <bean id="car1" class="factory.StaticCarFactory" factory-method="getCar"><constructor-arg value="aodi"></constructor-arg> </bean> </beans>
主方法
package factory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext ac=new ClassPathXmlApplicationContext("beans-factory.xml"); Car car=(Car) ac.getBean("car1"); System.out.println(car); } }