《Spring Recipes》第二章笔记:Creating Beans by Invokin...

《Spring Recipes》第二章笔记:Creating Beans by Invoking an Instance Factory Method


问题

用户希望使用工厂类来实例化bean。

解决方案

Spring的bean元素中提供了factory-bean属性来配置工厂类,factory-method属性来配置工厂方法。

例:
facroty-bean:定义返回bean实例的工厂方法。
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("Unknown product");
    }
}

配置文件: 使用工厂类时,需要将class设置为工厂类,并设置factory-method为工厂类中实例化bean的工厂方法。
<beans ...>
	<bean id="productCreator" class="com.apress.springrecipes.shop.ProductCreator">
		<property name="products">
			<map>
				<entry key="aaa">
					<bean class="com.apress.springrecipes.shop.Battery">
						<property name="name" value="AAA" />
						<property name="price" value="2.5" />
					</bean>
				</entry>
				<entry key="cdrw">
					<bean class="com.apress.springrecipes.shop.Disc">
						<property name="name" value="CD-RW" />
						<property name="price" value="1.5" />
					</bean>
				</entry>
			</map>
		</property>
	</bean>

	<bean id="aaa" factory-bean="productCreator" factory-method="createProduct">
		<constructor-arg value="aaa" />
	</bean>
	
	<bean id="cdrw" factory-bean="productCreator" factory-method="createProduct">
		<constructor-arg value="cdrw" />
	</bean>

</beans>


你可能感兴趣的:(spring)