如何在带有注释的地图中设置枚举键

如何在带有注释的地图中设置枚举键

本文介绍了Spring - 如何在带有注释的地图中设置枚举键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个枚举类

public enum MyEnum{
    ABC;
}

比我的 'Mick' 班级有这个属性

than my 'Mick' class has this property

private Map<MyEnum, OtherObj> myMap;

我有这个 spring xml 配置.

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>

这很好.
我想用 Spring 注解替换这个 xml 配置.
您对如何自动连接地图有任何想法吗?

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?

这里的问题是,如果我从 xml 配置切换到 @Autowired 注释(在 Mick 类的 myMap 属性上),Spring 会抛出这个异常

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 不再能够将字符串 ABC 识别为 MyEnum.ABC 对象.
有什么想法吗?

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

谢谢

推荐答案

这对我有用...

我的 Spring 应用上下文:

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>

Map 被注入的班级:

public class MyClass {

    private @Resource Map<MyEnum, String> myMap;
}

需要注意的重要一点是,在 Spring 上下文中,我使用了 SpEL(Spring 表达式语言),它仅在 3.0 版之后才可用.在我的课堂上,我使用了 @Resource,既不是 @Inject(它对我不起作用)也不是 @Autowired(我没有试试这个).我知道 @Resource@Autowired 之间的唯一区别是前者按 bean 名称自动注入,而后者按 bean 类型自动注入.

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.

享受吧!

这篇关于Spring - 如何在带有注释的地图中设置枚举键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 09:06