春天 - 你如何在注释的地图设置枚举密钥 [英] Spring - How do you set Enum keys in a Map with annotations

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

问题描述

我有一个枚举类

public enum MyEnum{
    ABC;
}

比我的'米克·'类有这个属性。

than my 'Mick' class has this property

private Map<MyEnum, OtherObj> myMap;

我有这个春天的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注解(在米克类的MYMAP属性)春引发此异常

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]

春天是不再能够识别ABC字符串作为MyEnum.ABC对象。

任何想法?

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

感谢

推荐答案

这工作对我来说...

This worked for me...

我的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>

我的班,其中地图被注入了:

public class MyClass {

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

要注意的重要的事情是,在Spring上下文我用规划环境地政司(春季前pression语言),这是因为只有3.0版本。而在我的班级我用 @Resource ,既不 @Inject (它没有为我工作),也不 @Autowired (我没有尝试这一点)。我所知道的唯一的区别之间的 @Resource @Autowired ,是前者由豆自动注入名字虽然后来被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.

享受!

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆