Define global lists, sets and maps in Spring configuration
Sometimes you may need to define stand-alone collections–lists, maps and sets–in your Spring XML configuration files, so that your beans can reference them as properties. This is easy to do using the util
schema. For example, let’s say you want to define a set of credit scores in your applicationContext.xml file:
<util:set id="creditScores"> <value>600</value> <value>710</value> <value>760</value> </util:set> |
Now you can reference the set in your beans, like so:
<bean id="creditBean" class="com.this.is.my.CreditBean"> <property name="myScores"> <ref local="creditScores"/> </property> </bean> |
Or try it again, using the p
schema, which provides more concise property definitions for your beans:
<bean id="creditBean" class="com.this.is.my.CreditBean" p:myScores-ref="creditScores" /> |
Controlling the data types in your collections
By default, Spring treats values as String
s. To enforce a datatype, use the type attribute. To control which collection implementation your collection uses, you can use the set-class attribute. You may not find Spring’s default choices preferable. For example, Spring uses LinkedHashSet
for sets by default to preserve the order you specify in your configuration. You may instead want to use HashSet
or TreeSet
. Here are our credit scores again, this time explicitly defining the data type and collection class:
<util:set id="creditScores" set-class="java.util.HashSet"> <value type="int">600</value> <value type="int">710</value> <value type="int">760</value> </util:set> |
Now you’ve defined a global, stand-alone collection with explicit data types, to be referenced by your other Spring beans! Just remember, if you are using the util
schema, to include the proper schema definition in your root element of the applicationContext.xml.