我正在尝试用 Spring 3.2.4 定义一个映射 bean,以 Enum 作为键类型,这样:
<util:map id="myMapping" key-type="com.acme.MyEnum">
<entry key="ENUM1" value="value1" />
<entry key="ENUM2" value="value2" />
</util:map>
MyEnum 类是一个普通类:
public enum MyEnum
{
ENUM1,
ENUM2
}
当创建应用程序上下文时,Spring 抛出这个异常:
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'myMapping':
Error converting typed String value for bean property 'sourceMap';
nested exception is org.springframework.beans.ConversionNotSupportedException:
Failed to convert value of type 'java.lang.String' to required type
'com.acme.MyEnum'; nested exception is java.lang.IllegalStateException:
Cannot convert value of type [java.lang.String] to required type
[com.acme.MyEnum]: no matching editors or conversion strategy found
(格式化以提高可读性)
由于给定的键类型,我希望 Spring 将字符串“ENUM1”转换为“MyEmum.ENUM1”
key-type="com.acme.MyEnum"
在映射 bean 声明中。
我知道如何通过使用 <entry>
进行替代 bean 定义来解决此问题,使用枚举的完全限定类名等......但我想按照描述构建定义以便于阅读。
这是已知错误还是我缺乏理解?
非常感谢您的帮助!
最佳答案
您可以尝试使用此策略进行字符串转换。
public enum MyEnum
{
ENUM1("ENUM1"),
ENUM2("ENUM2")
}
关于java - 尽管指定了 'key-type',但 Spring 3.2.4 无法在 <util :map. ../> 中将 String 转换为 Enum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26947183/