1. 程式人生 > >spring通過呼叫靜態工廠方法建立Bean

spring通過呼叫靜態工廠方法建立Bean

一:靜態工廠方法

1.呼叫靜態工廠方法建立Bean是將物件建立Bean的建立過程封裝到靜態方法中,當客戶端需要物件時,只需要簡單的呼叫靜態方法,而不關心建立物件的細節。

2.要宣告通過靜態方法建立的Bean,需要在Bean的class屬性裡指定擁有該工廠方法的類,同時在factory-method屬性裡指定工廠方法的名稱,最後使用constructor-arg元素為該方法傳遞引數。

二:程式碼實現

1.建立一個Car類

package com.dhx.factory;

public class Car {
		private String brand;
		private double price;
		public Car(String brand, double price) {
			super();
			this.brand = brand;
			this.price = 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 + "]";
		}
		
}

2.建立靜態工廠

package com.dhx.factory;

import java.util.HashMap;
import java.util.Map;

/**
 * 靜態工廠方法:直接呼叫某一個類的靜態方法就可以返回Bean的例項
 * @author Administrator
 *
 */
public class StaticCarFactory {
	private static Map<String,Car> cars=new HashMap<String,Car> ();
	
	static {
		cars.put("audi", new Car("audi", 30000));
		cars.put("baoma", new Car("baoma", 40000));
	}
	//靜態工廠方法
	public static Car getCar(String name) {
		return cars.get(name);
	}
}

 3.配置XML檔案(beans-factory.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"
	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="car"
		class="com.dhx.factory.StaticCarFactory"
		factory-method="getCar">
		<constructor-arg value="baoma"></constructor-arg>
		</bean>
</beans>

4.測試

package com.dhx.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 car=(Car) ctx.getBean("car");
		System.out.println(car);
		
	}

}