Spring入门学习——调用一个实例工厂方法创建Bean

来源:互联网 发布:我的世界透视矿物js 编辑:程序博客网 时间:2024/05/22 00:25
使用实例工厂方法在Spring IoC容器中创建一个Bean,目的是在另一个对象实例的一个方法中封装对象创建过程。
Spring支持调用实例工厂方法创建Bean。Bean实例在factory-bean属性中指定,而工厂方法仍然在factory-method属性中指定。

应用场景:我们仍然在之前的商品折扣代码基础进行修改学习:代码看这里 ,这次我们使用Map存储预定义产品,然后通过编写ProductCreator类,在其实例工厂方法createProduct()中通过在Map中搜索提供的产品ID,寻找一个产品。

package com.cgy.springrecipes.shop;

import java.util.Map;

public class ProductCreator {

private Map<String,Product> products;

public void setProducts(Map<String, Product> products) {
this.products = products;
}

public Product createProduct(String productId) {
Product product = products.get(productId);
if(product != null) {
return product;
}
throw new IllegalArgumentException("Unkonw product");
}
}

上面的代码实现了需要的场景,现在需要修改之前的配置文件,为了从ProductCreator类中创建产品,必须在IoC容器中声明该类一个实例,并且配置它的产品Map。修改后代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="productCreator" class="com.cgy.springrecipes.shop.ProductCreator">
<property name="products">
<map>
<entry key="kingston">
<bean class="com.cgy.springrecipes.shop.Battery">
<property name="name" value="kingston"/>
<property name="price" value="2.5"/>
</bean>
</entry>
<entry key="taylor">
<bean class="com.cgy.springrecipes.shop.Disc">
<property name="name" value="taylor"/>
<property name="price" value="1.5"/>
</bean>
</entry>
</map>
</property>
</bean>

<bean id="battery" factory-bean="productCreator" factory-method="createProduct">
<constructor-arg value="kingston"/>
</bean>

<bean id="disc" factory-bean="productCreator" factory-method="createProduct">
<constructor-arg value="taylor"/>
</bean>

</beans>


上面的xml配置就是实例工厂方法的配置内容,对比静态工厂实例方法的·配置内容 多了点(就算是除去了Map配置内容),在上面的实例工厂方法配置过程中,配置顺序如下:
(1)声明了一个ProudctCreator类的实例,因为我们需要从这里创建产品
(2)在ProductCreator实例中配置Map集合的内容,里面的内容就是我们所需要的产品,当然产品里面还要配置对应的产品名称和产品价格(使用内部Bean)
(3)尽管配置好了实例工厂方法所在的类实例,但是这时候还不能使用,因为Main函数并没有使用这个Bean,而是使用了Bean的id为“battery”和“disc”的两个Bean,因此需要再次配置两个Bean,这时候就需要在这两个Bean中配置factory-bean和factory-method指定实例和实例工厂方法。并且利用构造参数,往createProduct()方法传递产品id,从而利用ProductCreator创建产品。
0 0
原创粉丝点击