通过调用静态工厂方法创建Bean
- 调用静态工厂方法创建Bean是将对象创建的过程封装到静态方法中,当客户端需要对象时,只需要简单的调用静态方法,而不关心创建对象的细节。
- 要声明通过静态方法创建Bean,需要在Bean的class属性里指定拥有改工厂的方法的类,同时在factory-method属性里指定工厂方法的名称,最后使用元素为该方法传递方法参数
// src/beans.xml
<beans>
<bean id="car1" class="com.lijunyang.model.StaticCarFactory"
factory-method="getCar">
<constructor-arg value="audi" />
</bean>
<!-- 配置工厂实例 -->
<bean id="carFactory" class="com.lijunyang.model.InstanceCarFactory" />
<!-- 通过实例工厂获取Bean -->
<bean id="car2" factory-bean="carFactory" factory-method="getCar">
<constructor-arg value="ford" />
</bean>
</beans>
// src/com/lijunyang/model/StaticCarFactory.java
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("audi", 400000));
}
public static Car getCar(String name) {
return cars.get(name);
}
}
// src/com/lijunyang/model/InstanceCarFactory.java
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("audi", 400000));
}
public Car getCar(String name) {
return cars.get(name);
}
}
// src/com/lijunyang/test/Main.java
public class Main {
public static main(String args[]) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml")
Car car1 = (Car) ctx.getBean("car1");
System.out.println(car1);
Car car2 = (Car) ctx.getBean("car2");
System.out.println(car2);
}
}
FactoryBean
// org.springframework.beans.factory.FactoryBean.java具有3个方法
public interface FactoryBean<T> {
T getObject() throws Exception;
Class<?> getObjectType();
boolean isSingleton();
}
// src/beans.xml
<beans>
<!-- 通过FactoryBean 来配置Bean的实例
class:指向FactoryBean的全类名
property: 配置FactoryBean的属性
但实际返回的实例确实 FactoryBean的getObject()方法返回的实例!
-->
<bean id="car" class="com.lijunyang.model.CarFactoryBean">
<property name="brand" value="BMW" />
</bean>
</beans>
// src/com/lijunyang/model/CarFactoryBean.java
import org.springframework.beans.factory.FactoryBean;
public class CarFactoryBean implements FactoryBean {
private String brand;
public setBrand(String brand) {
this.brand = brand;
}
// 返回Bean对象
@Override
public Car getObject() throws Exception {
return new Car(brand, 500000);
}
// 返回Bean的类型
@Override
public Class<?> getObjectType() {
return Car.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
// src/com/lijunyang/test/Main.java
public class Main {
public static main(String args[]) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml")
Car car1 = (Car) ctx.getBean("car");
System.out.println(car1);
}
}