Java 如何在 Spring XML 配置文件类中为 Map 属性指定?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19436987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 17:08:40  来源:igfitidea点击:

How to specify in Spring XML configuration file class for a Map property?

javaspring

提问by Sachin Thapa

Here is what I mean, see following spring XML file:

这就是我的意思,请参阅以下 spring XML 文件:

<bean id = 'a' class="A">
   <property name="mapProperty">
       <map>
          <entry key="key1"><value>value1</value></entry>
       </map>
   </property>
</bean>

And my class looks like following:

我的课程如下所示:

class A {
   HashMap mapProperty

}

How can I tell in spring XML file that Map to be injected is of type java.util.HashMap ? Or in general can I provide class name for the Map ?

如何在 Spring XML 文件中判断要注入的 Map 是 java.util.HashMap 类型?或者一般我可以为 Map 提供类名吗?

Please note, I cannot change the class Ato use Mapinstead of HashMap

请注意,我无法更改class A使用Map而不是HashMap

Thanks in advance !!

提前致谢 !!

采纳答案by Sotirios Delimanolis

You can use util:map

您可以使用 util:map

<util:map id="someId" map-class="java.util.HashMap">
    <entry key="key1">
        <value>value1</value>
    </entry>
</util:map>

<bean id="a" class="A">
    <property name="mapProperty" ref="someId">
    </property>
</bean>

Don't forget to add the utilnamespace.

不要忘记添加util命名空间。

回答by Rohit Jain

You can use util:maptag from the utilschema. Here's an example:

您可以使用架构中的util:map标记util。下面是一个例子:

<util:map id="utilmap" map-class="java.util.HashMap">
    <entry key="key1" value="value1"/>
    <entry key="key2" value="value2"/>
</util:map>

<bean id = 'a' class="A">
   <property name="mapProperty" ref="utilmap" />
</bean>

BTW, you should not use raw type HashMap. Use a parameterized type instead - HashMap<String, String>.

顺便说一句,你不应该使用 raw type HashMap。改用参数化类型 - HashMap<String, String>

回答by dtk

To extend Sotirios Delimanolis' answer: See this exampleon how to include the utilnamespace:

要扩展Sotirios Delimanolis 的回答:请参阅有关如何包含命名空间的示例util

<?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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/util 
           http://www.springframework.org/schema/util/spring-util.xsd">
</beans>

Note that you will need to amend the schemaLocationas well ;)

请注意,您还需要修改schemaLocation;)