Declaring Beans from Static Fields

First, let’s define two product constants in the Product class.

package com.shop;
public abstract class Product {
public static final Product AAA = new Battery("AAA", 2.5);
public static final Product CDRW = new Disc("CD-RW", 1.5);
}

To declare a bean from a static field, you can make use of the built-in factory bean FieldRetrievingFactoryBean and specify the fully qualified field name in the staticField property.

<beans …>
<bean id="aaa" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">
<property name="staticField">
<value>com.shop.Product.AAA</value>
</property>
</bean>
<bean id="cdrw" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">
<property name="staticField">
<value>com.shop.Product.CDRW</value>
</property>
</bean>
</beans>

The preceding bean configuration is equivalent to the following code snippet:

Product aaa = com.shop.Product.AAA;
Product cdrw = com.shop.Product.CDRW;

As an alternative to specifying the field name in the staticField property explicitly, you can set it as the bean name of FieldRetrievingFactoryBean. The downside is that your bean name may get rather long and verbose.

<beans …>
<bean id="com.shop.Product.AAA"
class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean" />
<bean id="com.shop.Product.CDRW"
class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean" />
</beans>

Spring 2.x allows you to declare a bean from a static field by using the <util:constant> tag. Compared to using FieldRetrievingFactoryBean, it is a simpler way of declaring beans from static fields. But before this tag can work, you must add the util schema definition to your <beans> root element.

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-2.5.xsd">
<util:constant id="aaa"
static-field="com.shop.Product.AAA" />
<util:constant id="cdrw"
static-field="com.shop.Product.CDRW" />
</beans>