Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

spring

Here is what I mean, see 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 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 ?

Please note, I cannot change the class A to use Map instead of HashMap

Thanks in advance !!

like image 804
Sachin Thapa Avatar asked Oct 17 '13 20:10

Sachin Thapa


People also ask

Which attributes are required for property tag in XML based Spring configuration?

In XMLbased configuration metadata, you use the id and/or name attributes to specify the bean identifier(s). This attribute specifies the scope of the objects created from a particular bean definition and it will be discussed in bean scopes chapter.

How do you do annotation based configuration in XML Spring?

Starting from Spring 2.5 it became possible to configure the dependency injection using annotations. So instead of using XML to describe a bean wiring, you can move the bean configuration into the component class itself by using annotations on the relevant class, method, or field declaration.


1 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>

Don't forget to add the util namespace.

like image 191
Sotirios Delimanolis Avatar answered Nov 14 '22 21:11

Sotirios Delimanolis