Search code examples
springenumsannotations

Spring - How do you set Enum keys in a Map with annotations


I've an Enum class

public enum MyEnum{
    ABC;
}

than my 'Mick' class has this property

private Map<MyEnum, OtherObj> myMap;

I've this spring xml configuration.

<util:map id="myMap">
    <entry key="ABC" value-ref="myObj" />
</util:map>

<bean id="mick" class="com.x.Mick">
    <property name="myMap" ref="myMap" />
</bean>

and this is fine.
I'd like to replace this xml configuration with Spring annotations.
Do you have any idea on how to autowire the map?

The problem here is that if I switch from xml config to the @Autowired annotation (on the myMap attribute of the Mick class) Spring is throwing this exception

nested exception is org.springframework.beans.FatalBeanException: Key type [class com.MyEnum] of map [java.util.Map] must be assignable to [java.lang.String]

Spring is no more able to recognize the string ABC as a MyEnum.ABC object.
Any idea?

Thanks


Solution

  • This worked for me...

    My Spring application context:

    <util:map id="myMap">
      <entry key="#{T(com.acme.MyEnum).ELEM1}" value="value1" />
      <entry key="#{T(com.acme.MyEnum).ELEM2}" value="value2" />
    </util:map>
    

    My class where the Map gets injected:

    public class MyClass {
    
        private @Resource Map<MyEnum, String> myMap;
    }
    

    The important things to note are that in the Spring context I used SpEL (Spring Expression Language) which is only available since version 3.0. And in my class I used @Resource, neither @Inject (it didn't work for me) nor @Autowired (I didn't try this). The only difference I'm aware of between @Resource and @Autowired, is that the former auto-inject by bean name while the later does it by bean type.

    Enjoy!