Creating Beans by Invoking a Static Factory Method

You can write the following createProduct() static factory method to create a product from a predefined product ID. According to the product ID, this method will decide which concrete product class to instantiate. If there is no product matching this ID, it will throw an IllegalArgumentException.

package com.shop;
public class ProductCreator {
public static Product createProduct(String productId) {
if ("aaa".equals(productId)) {
return new Battery("AAA", 2.5);
} else if ("cdrw".equals(productId)) {
return new Disc("CD-RW", 1.5);
}
throw new IllegalArgumentException("Unknown product");
}
}

To declare a bean created by a static factory method, you specify the class hosting the factory method in the class attribute and the factory method’s name in the factory-method attribute. Finally, you pass the method arguments by using the <constructor-arg> elements.

<beans …>
<bean id="aaa" class="com.shop.ProductCreator"
factory-method="createProduct">
<constructor-arg value="aaa" />
</bean>
<bean id="cdrw" class="com.shop.ProductCreator"
factory-method="createProduct">
<constructor-arg value="cdrw" />
</bean>
</beans>

In case of any exception thrown by the factory method, Spring will wrap it with a BeanCreationException. The equivalent code snippet for the preceding bean configuration is shown following:

Product aaa = ProductCreator.createProduct("aaa");
Product cdrw = ProductCreator.createProduct("cdrw");