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 {
 EN, FR
}

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:

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

That'it! Spring does the rest…

3 comments:

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

    ReplyDelete
  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){
    this.name=name;
    }
    public getLanguageName(){
    return name;
    }
    }

    How can I use the function getLanguageName in spring?

    Thanks

    ReplyDelete
    Replies
    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.

      Delete