Inject Java 5 Enums with Spring
This is a quick entry about how to "inject" a Java 5 enum using the Spring Framework. This may not be a common problem, or even considered an obstacle for the average Spring user. I wouldn't consider myself an average Spring user as my involvement with Spring is limited to a small domain of the product I work on. Either way, I thought it would be nice to share my solution with others...
The main players in this example are:
- Status.java - The Java 5 Enum with two enumerations: ACTIVE and PENDING
- AccountServiceImpl.java - The "service" class to have it's defaultStatus property value injected via dependency injection.
- applicationContext.xml - The Spring Framework configuration file.
Until I can find a good way to embed code/xml in WordPress, the code will only be viewable via the links provided.
You'll notice in the applicationContext.xml that the Status enum has been configured twice. Once as it's own bean, Status.ACTIVE, and the other as an anonymous "inner bean" of the accountService bean's defaultStatus property value. In either case you'll notice that each bean definition declares the attribute, factory-method="valueOf". This declaration tells the Spring Framework to use the static factory method, valueOf on the Enum class. We'll also declare a constructor-arg value with the name of the enum, either ACTIVE or PENDING. In short, the enum will be constructed using the Status.valueOf( "ACTIVE" ), or Status.valueOf( "PENDING" ).
The sample code and eclipse project can be downloaded in it's entirety here. This project requires Spring Framework 1.2.8 and Commons - Logging. Oh... and of course, JUnit.







Try Spring 2. Support is built in:
<bean class=”scratch.spring.EnumyBean” p:beanoEnum=”AFTER”/>
Thank you so much for your solution. I’m very new to Spring.
I thought by v. 2.0 it should be easy enough to do something like:
com.orsomethinglikethat.example.model.Status.PENDING
Apparently not!
You da man, for writing this up.
Hmm.. the XML for my example got munged.. oh well