[英]How to specify in Spring XML configuration file class for a Map property?
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 ? 如何在spring XML文件中告诉要注入的Map是java.util.HashMap类型? Or in general can I provide class name for the Map ?
或者一般来说我可以为地图提供课程名称吗?
Please note, I cannot change the class A
to use Map
instead of HashMap
请注意,我无法更改
class A
以使用Map
而不是HashMap
Thanks in advance !! 提前致谢 !!
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 util
namespace. 不要忘记添加
util
命名空间。
You can use util:map
tag from the util
schema. 您可以使用
util
模式中的util:map
标记。 Here's an example: 这是一个例子:
<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
. 顺便说一下,你不应该使用原始类型的
HashMap
。 Use a parameterized type instead - HashMap<String, String>
. 使用参数化类型 -
HashMap<String, String>
。
To extend Sotirios Delimanolis' answer : See this example on how to include the util
namespace: 扩展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 schemaLocation
as well ;) 请注意,您还需要修改
schemaLocation
;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.