For example, let's say we have defined an enum class as follows:
package robertmaldon.cafe;
public enum Coffee {
MOCHA,
ESPRESSO,
LATTE,
FRAPPUCCINO;
}
The Spring XML config for a bean instance then looks something like this:
<bean id="latte" class="robertmaldon.cafe.Coffee" factory-method="valueOf">
<constructor-arg>
<value>LATTE</value>
</constructor-arg>
</bean>
NOTE: Declaring the bean scope as prototype or singleton makes no difference. For the same class loader a singleton bean is always returned.
If you don't want to declare a bean for each value of an enum you can simply use the enum value name at the point where it is injected into a dependent class. For example, let's say you have a class that is injected with an instance of our enum above:
package robertmaldon.cafe;
public class CoffeeMachine {
private Coffee coffee;
public void setCoffee(Coffee coffee) {
this.coffee = coffee;
}
}
In the Spring XML config simply use the enum value as the property value (apparently works with Spring 1.2.2 and beyond):
<bean id="machine" class="robertmaldon.cafe.CoffeeMachine">
<property name="coffee" value="MOCHA"/>
</bean>