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

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

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

And my class is as follows:

class A {
   HashMap mapProperty

}

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

Please note: I cannot change class Ato use MapinsteadHashMap

Thanks in advance!

+6
source share
3 answers

you can use 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>

Remember to add a namespace util.

+7
source

You can use the util:maptag util. Here is 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>

, HashMap. - HashMap<String, String>.

+4

To expand on Sotirios Delimanolis answer : see this example on how to include a namespace 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>

Please note that you will also need to change schemaLocation;)

0
source

All Articles