Wiring Sets, Maps and Properties in Spring
by, 11-16-2011 at 05:19 PM (5374 Views)
Similarly to lists, there are times when you will need to map to other types of collections. In this tip, I will outline what you need to do to wire sets, maps and properties. The key to remember is that you want to wire your bean to the same type that is being used in the class definition. So if your bean has a java.util.Set property to guarantee uniqueness in the collection, you want to use the same definition in the xml definition.
So for example, if you want to use a java.util.Set, then you use the <set> element in your definition. It is used exactly as it is with a list or array:
Notice that you use <set> exactly the way you would use <list>. The only difference is in how it is wired to a bean property. Where <list> wires values to a java.util.List or an array, <set> wires values to a java.util.Set.Java Code:<property name=”carEntertainmentSet”> <set> <value>DVD Player</value> <ref bean=” carEntertainment”/> </set> </property>
If you want to use java.util.Map collections in Spring, this time you use the <map> element. Note that in contrast to Lists or Sets, each entry in the Map is made up of a key and a value pairs. This is defined by the <entry> element:
Here we have a map being wired into the Spring configuration. The value of a map <entry>, is a valid property element. Note that although in this case we are using a reference to an object (<ref>, it is equally valid to use <value>, <list>, or even another <map>. The first part of wiring an <entry>, involves providing the key attribute of type String. This is a minor limitation over the full functionality of java.util.Map, which allows any object to be the key of a map entry. However, this limitation doesn’t often present a problem, as Maps are typically keyed with Strings.Java Code:<property name=”carSeatCoverMap”> <map> <entry key=”blue”> <ref bean=”seatCover1”/> </entry> <entry key=”beige”> <ref bean=”seatCover2”/> </entry> </map> </property>
Finally if you want to wire properties using a java.util.Properties collection you must wire it with the <props> element. Each element of a properties collection is wired with the <prop> element.
Note that although it has similarities with the map element, property entry values always map to a String.Java Code:<property name="specifications"> <props> <prop key="/viewCarDetails.htm">viewCarDetailController</prop> </props> </property>
So there is little need to use the <value> element to differentiate between String values and non-String values. Properties are frequently used for URL mapping especially with Spring Model/View/Controller (MVC) framework as shown above.