Spring 的靜態工廠及例項工廠的使用 重溫自己對於Spring 的理解
靜態工廠方法:直接呼叫靜態方法可以返回Bean的例項
package com.zw.factory;
import java.util.HashMap;
import java.util.Map;
public class StaticCarFactory {
/**
* 靜態工廠方法:直接呼叫靜態方法可以返回Bean的例項
*
*/
private static Map<String ,Car > cars=new HashMap<String , Car>();
static{
cars.put("audi", new Car(3000, "aodi"));
cars.put("fodo", new Car(3000, "aodi"));
}
//靜態工廠方法
public static Car getCar(String name){
return cars.get(name);
}
}
例項工廠方法。即呼叫工廠本身,再呼叫工廠的例項方法來返回bean例項
package com.zw.factory;
import java.util.HashMap;
import java.util.Map;
public class InstanceCarFactory {
/**
* 例項工廠方法。即呼叫工廠本身,再呼叫工廠的例項方法來返回bean例項
*/
private Map<String ,Car> cars=null;
public InstanceCarFactory() {
// TODO Auto-generated constructor stub
cars=new HashMap<String, Car>();
cars.put("audi", new Car(1000,"audi"));
cars.put("dffdas", new Car(2000,"audi"));
}
public Car getCar(String brand){
return cars.get(brand);
}
}
beans-zwfactory.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
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" factory-method="getCar"
class="com.zw.factory.StaticCarFactory">
<constructor-arg value="audi"></constructor-arg>
</bean>
<!-- 配置工廠的例項 -->
<bean id="carFactory" class="com.zw.factory.InstanceCarFactory">
</bean>
<bean id="car2" factory-bean="carFactory" factory-method="getCar">
<constructor-arg value="audi"></constructor-arg>
</bean>
</beans>
Car.java實體類
package com.zw.factory;
public class Car {
private double price;
private String brand;
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
@Override
public String toString() {
return "Car [brand=" + brand + ", price=" + price + "]";
}
public Car(){
System.out.println("cars....constructor");
}
public Car(double price, String brand) {
super();
this.price = price;
this.brand = brand;
}
}
Main.java 測試
package com.zw.factory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext cx=new ClassPathXmlApplicationContext("beans-factory.xml");
Car car1=(Car) cx.getBean("car1");
System.out.println(car1);
Car car2=(Car) cx.getBean("car2");
System.out.println(car2);
}
}
執行結果:
Car [brand=aodi, price=3000.0]
Car [brand=audi, price=1000.0]