Spring初学之通过工厂方法配置Bean

时间:2021-08-15 17:01:35

工厂方法配置bean分为两种,一种是实例工厂方法,另一种是静态工厂方法。

先来看看实体bean:

Car.java:

package spring.beans.factory;

public class Car {
private String name;
private int price;
public Car(String name, int price) {
super();
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public String toString() {
return "Car [name=" + name + ", price=" + price + "]";
}
}

一、实例工厂方法配置bean

InstanceBeanFactory.java:
package spring.beans.factory;

import java.util.HashMap;
import java.util.Map; /**
* 实例工厂方法
* @author Administrator
*
*/
public class InstanceBeanFactory {
private Map<String, Car> map=null; public InstanceBeanFactory() {
map=new HashMap<String, Car>();
map.put("奥迪", new Car("奥迪", 300000));
map.put("福特", new Car("福特", 400000));
} public Car getCar(String name){
return map.get(name);
} }

spring的xml配置文件核心代码:

    <!-- 配置实例工厂方法的bean -->
<bean id="instanceFactory" class="spring.beans.factory.InstanceBeanFactory"></bean> <!-- 通过实例工厂方法创建bean -->
<bean id="car2" factory-bean="instanceFactory" factory-method="getCar">
<constructor-arg value="福特"></constructor-arg>
</bean>

二、静态方法配置bean

StaticBeanFactory.java:
package spring.beans.factory;

import java.util.HashMap;
import java.util.Map; /**
* 通过静态工厂方法创建bean
* @author Administrator
*
*/
public class StaticBeanFactory {
private static Map<String, Car> map=new HashMap<String, Car>();
static{
map.put("长安", new Car("长安", 30000));
map.put("奥迪", new Car("奥迪", 300000));
} public static Car getCar(String name){ return map.get(name);
}
}

spring的xml配置文件核心代码:

    <!-- 通过静态工厂方法创建bean -->
<bean id="car" class="spring.beans.factory.StaticBeanFactory"
factory-method="getCar">
<constructor-arg value="奥迪"></constructor-arg> </bean>

测试方法:

package spring.beans.factory.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import spring.beans.factory.Car; 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); Car car1=(Car) ctx.getBean("car2");
System.out.println(car1);
} }

输出:

Car [name=奥迪, price=300000]
Car [name=福特, price=400000]