<?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="car1"
class="com.atguigu.spring.beans.factory.StaticCarFactory"
factory-method="getCar">
<constructor-arg value="audi"></constructor-arg>
</bean>
<!-- 配置工厂的实例 -->
<bean id="carFactory" class="com.atguigu.spring.beans.factory.InstanceCarFactory"></bean>
<!-- 通过实例工厂方法配置 bean -->
<bean id="car2" factory-bean="carFactory" factory-method="getCar">
<constructor-arg value="ford"></constructor-arg>
</bean>
</beans>
package com.atguigu.spring.beans.factory;
import java.util.HashMap;
import java.util.Map;
/**
* 实例工厂方法:实例工厂的方法. 即先需要创建工厂本身,在调用工厂的实例方法来返回bean的实例
*
*/
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("ford", 400000));
}
public Car getCar(String brand) {
return cars.get(brand);
}
}
package com.atguigu.spring.beans.factory;
import java.util.HashMap;
import java.util.Map;
/**
* 静态工厂方法:
* 直接调用某一个类的静态方法就可以返回 bean 的实例(可以在不创建StaticCarFactory对象的方法下通过静态工厂方法就可以返回 bean 的实例)
*/
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("ford", 400000));
}
//静态工厂方法
public static Car getCar(String name) {
return cars.get(name);
}
}
package com.atguigu.spring.beans.factory;
public class Car {
private String brand;
private double 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 + "]";
}
public Car() {
System.out.println("容器被创建...");
// TODO Auto-generated constructor stub
}
public Car(String brand, double price) {
super();
this.brand = brand;
this.price = price;
}
}
package com.atguigu.spring.beans.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("car1");
System.out.println(car);
Car car2 = (Car) ctx.getBean("car2");
System.out.println(car2);
}
}
原文地址:http://blog.51cto.com/13416247/2084991