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…