在Spring bean中定义枚举映射

时间:2013-02-20 02:26:50

标签: java spring dictionary dependency-injection

我正在尝试在我的Spring bean xml中定义枚举映射,我希望它在xml中填充,但是当我尝试像这样定义它时

<bean class = "java.util.EnumMap">
    <constructor-arg>
        <util:map key-type="org.itemlist.products.stockitem">
            <entry key="stockitem.SOAP">100</entry>
        </util:map> 
    </constructor-arg>

更新

这是我的bean配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util-3.0.xsd">


    <bean class = "java.util.EnumMap">
        <constructor-arg>
            <util:map key-type="org.itemlist.products.stockitem">
                <entry key="stockitem.SOAP">100</entry>
            </util:map> 
        </constructor-arg>
    </bean>

</beans>

当我在条目中添加一个值时,现在就是错误

cvc-complex-type.2.3: Element 'entry' cannot have character [children], because the type's content type is element-only.

3 个答案:

答案 0 :(得分:4)

您是否在标题中定义了这些架构:

http://www.springframework.org/schema/util 
http://www.springframework.org/schema/util/spring-util-3.0.xsd

名称空间:

xmlns:util="http://www.springframework.org/schema/util"

答案 1 :(得分:0)

该错误消息表示entry元素必须为空,即不包含任何文本或其他元素。您想要的语法是:

<entry key="stockitem.SOAP" value="100"/>

entry元素还允许您将对另一个bean的引用作为值传递,例如:

<entry key="stockitem.SOAP" value-ref="myOtherBean"/>

(在你的情况下这是没用的,我只是提到完整性)

答案 2 :(得分:0)

您可以这样定义它:

    <bean id="springBean" class="a.b.c.d.MyEnum">
        <constructor-arg>
            <util:map key-type="a.b.c.d.MyEnum" value-type="aa.b.c.d.Mya.b.c.d.MyVal">
                <entry>
                    <key><value type="a.b.c.d.MyEnum">ENUM-VAL1</value></key>
                    <ref bean="myValBean1" />
                </entry>
                <entry>
                    <key><value type="a.b.c.d.MyEnum">ENUM-VAL1</value></key>
                    <ref bean="myValBean1" />
                </entry>
            </util:map>
        </constructor-arg>
    </bean>