Spring通過工廠方法配置Bean
阿新 • • 發佈:2018-12-09
前言:
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}