Thursday, July 22, 2010

Injecting enums with the Spring Framework

Today I needed to inject an Enum into a bean's constructor using Spring.

First I thought I'd need to write my own FactoryBean or 'better' a PropertyEditor.

Well no need, it is already nicely handled by the framework. After a bit of googling, I found the documentation in Appendix A of Spring's reference

And here is what actually works just fine. If I have the following enum:

public enum Language {

And the following class that I need to instantiate with Spring:

public class LocalisedLogger {
 private final Language lang;
 public LocalisedLogger(Language lang) {
   this.lang = lang;

Then I can just configure it like this:

 <bean id="logger" class="org.leberrigaud.example.LocalisedLogger">
   <constructor-arg value="FR">

That'it! Spring does the rest…


  1. Thanks! Way better than the valueOf static method approach.

  2. Thanks for the example.
    I have one question actually two..
    1.Instead of passing
    How can I pass Language.FR?
    2.If I define the enum like
    public enum Language {
    EN("English"), FR("French");
    private String name;
    Language(String name){;
    public getLanguageName(){
    return name;

    How can I use the function getLanguageName in spring?


    1. 1. I don't know. I'm not sure why you would want to do this, since the enum type is already given by the constructor in our case.

      2. I don't know either. I don't see what is has to do with injecting enums. Why don't you inject the enum and then call the appropriate method. This will use stronger typing and is better IMHO.