Spring - 如何在带有注释的 Map 中设置 Enum 键 [英] Spring - How do you set Enum keys in a Map with annotations

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

问题描述

我有一个枚举类

公共枚举 MyEnum{ABC;}

比我的Mick"类有这个属性

private Map我的地图;

我有这个 spring xml 配置.

<entry key="ABC" value-ref="myObj"/></util:map><bean id="mick" class="com.x.Mick"><property name="myMap" ref="myMap"/></bean>

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

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

 嵌套异常是 org.springframework.beans.FatalBeanException:映射 [java.util.Map] 的键类型 [class com.MyEnum] 必须可分配给 [java.lang.String]

Spring 不再能够将字符串 ABC 识别为 MyEnum.ABC 对象.
有什么想法吗?

谢谢

解决方案

这对我有用...

我的 Spring 应用程序上下文:

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

Map 被注入的我的类:

public class MyClass {私有@Resource Map<MyEnum, String>我的地图;}

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

享受吧!

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

解决方案

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!

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

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