标签:style blog http java color 使用
概要:
通过调用静态工厂方法创建Bean
package com.coslay.beans.factory; public class Car { private String brand; private double price; public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Override public String toString() { return "Car [brand=" + brand + ", price=" + price + "]"; } public Car() { System.out.println("Car's Constructor..."); } public Car(String brand, double price) { super(); this.brand = brand; this.price = price; } }
package com.coslay.beans.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("audi", new Car("audi",300000)); cars.put("ford", new Car("ford",400000)); } //静态工厂方法 public static Car getCar(String name){ return cars.get(name); } }
package com.coslay.beans.factory; import java.util.HashMap; import java.util.Map; /* *实例工厂方法:实例工厂的方法,即先须要创建工厂本身,再调用工厂的实例方法来返回bean的实例 */ public class InstanceCarFactory { private Map<String,Car> cars =null; public InstanceCarFactory(){ cars = new HashMap<String,Car>(); cars.put("audi", new Car("audi",300000)); cars.put("ford",new Car("ford",400000)); } public Car getCar(String brand){ return cars.get(brand); } }
package com.coslay.beans.factory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-factory.xml"); Car car1 = (Car) ctx.getBean("car1"); System.out.println(car1); Car car2 = (Car) ctx.getBean("car2"); System.out.println(car2); } }
<?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.xsd"> <!-- 通过静态工厂方法来配置bean,注意不是配置静态工厂方法实例,而是配置bean实例 --> <!-- class属性:指向静态工厂方法的全类名 factory-method:指向静态工厂方法的名字 constructor-arg:假设工厂方法须要传入參数,则使用constructor-arg来配置參数 --> <bean id="car1" class="com.coslay.beans.factory.StaticCarFactory" factory-method="getCar"> <constructor-arg value="audi"></constructor-arg> </bean> <!-- 配置工厂的实例 --> <!-- class属性:指向实例工厂方法的全类名 factory-method:指向静态工厂方法的名字 constructor-arg:假设工厂方法须要传入參数,则使用constructor-arg来配置參数 --> <bean id="carFactory" class="com.coslay.beans.factory.InstanceCarFactory"></bean> <!-- 通过实例工厂方法来配置bean --> <bean id="car2" factory-bean="carFactory" factory-method="getCar"> <constructor-arg value="ford"></constructor-arg> </bean> </beans>
spring 通过工厂方法配置Bean,布布扣,bubuko.com
标签:style blog http java color 使用
原文地址:http://www.cnblogs.com/hrhguanli/p/3851500.html