前言:
Spring配置Bean的方法有很多,这里只介绍通过工厂方法配置Bean。
所谓工厂即含有批量的Bean,可根据传入的参数条件返回对应的Bean实例。
工厂又分两种:
静态工厂通过静态方法返回Bean实例。
实例工厂通过实例方法返回Bean实例。
区别两者:
前者配置Bean的时候是配置实例Bean,而不是静态工厂。
后者配置Bean的时候需要先配置实例工厂,然后根据传参来配置实例Bean
先来介绍第一种方法:静态工厂
直接调用某一个类的静态方法就可以返回Bean实例
先创建静态工厂类
public class MyStaticFctory {
private static Map<String,Car> cars = new HashMap<String,Car>();
static{
cars.put("大众",new Car("大众",10000));
cars.put("奥迪",new Car("奥迪",40000));
}
public static Car getCar(String name){
return cars.get(name);
}
}
再配置xml配置文件:
通过静态工厂配置Bean,注意不是配置静态工厂实例,而是配置bean实例
<bean id="car" class="hello.MyStaticFctory" factory-method="getCar">
<constructor-arg value="奥迪"></constructor-arg>
</bean>
注意:
class:静态工厂全类名
factory-method:获得bean实例的静态方法。
constructor-arg:如果返回实例的静态方法有属性,就是它来赋值
测试:
public static void main(String[] args) throws SQLException {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Car car = (Car) applicationContext.getBean("car");
System.out.println(car);
}
输出:
Car{name='奥迪', price=40000}
第二种方法:实例工厂方法创建Bean
将对象的创建过程封装到另一个对象实例的方法离,
当客户端需要请求对象的时候,
只需要简单的调用该实例方法而不需要关心对象的创建过程。
实例工厂类:
public class MyFactory {
private Map<String,Car> cars = new HashMap<String,Car>();
public MyFactory(){
cars.put("大众",new Car("大众",10000));
cars.put("奥迪",new Car("奥迪",40000));
}
public Car getCar(String name){
return cars.get(name);
}
}
配置xml文件:
实例工厂的方法,需要创建工厂本身,再调用工厂的实例方法来返回bean的实例。
<bean id="myfactory" class="hello.MyFactory"></bean>
<bean id="car2" factory-bean="myfactory" factory-method="getCar">
<constructor-arg value="大众"></constructor-arg>
</bean>
测试:
public static void main(String[] args) throws SQLException {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Car car = (Car) applicationContext.getBean("car2");
System.out.println(car);
}
输出:
Car{name='大众', price=10000}
本文介绍了Spring中通过静态工厂和实例工厂方法配置Bean的过程。包括如何创建工厂类、配置XML文件及测试输出。
979

被折叠的 条评论
为什么被折叠?



