The following code showcases how we can instantiate collections inside application context files in Spring. I suppose we want to use a class DummyContainer as a bean and we instantiate the following collection type properties of this class (assume the appropriate setters are given). The class MyBean is defined elsewhere and its actual properties do not matter here. We use two instances of the class in order to demonstrate reference values and inplace bean definitions:

  • java.util.List<Object> aList;
    • Content:  [“Hello World”, new Double(1.3), new MyBean(), new MyBean()]
    • XML element: <list/>
  • java.util.Map<String, Object> aMap;
    • Content: [[“Item 1”, “Hello World”],[“Item 2”, new Double(1.3)],[“Item 3”, new MyBean()],[“Item 4”, new MyBean()]]
    • XML element: <map/> and <entry/>
  • java.util.Properties properties;
    • Content: [[“Prop 1”, “Value 1”]]
    • XML element: <props/> and <prop/>
  • java.util.Set<Object> aSet;
    • Content: [“Hello World”, new Float(1.3), new MyBean(), new MyBean()]
    • XML element: <set/>

This is how the context  file looks like:

<beans>
  <bean id="myBean" class="MyBean"/>
&nbsp; <bean id="dummyContainer" class="DummyContainer">
    <property name="aList">
      <list>
        <value>"Hello World"</value>
        <value>1.3</value>
        <ref id="myBean"/>
        <bean class="MyBean/>
      </list>
    </property>
    <property name="aMap">
      <map>
        <entry key="Item 1" value="Hello World"/>
        <entry key="Item 2" value="1.3"/>
        <entry key="Item 3" value-ref="myBean"/>
        <entry key="Item 4"><bean class="MyBean/></entry>
      </map>
    </property>
    <property name="properties">
      <props>
        <prop key="Prop 1">Value 1</prop>
      </props>
    </property>
    <property name="aSet">
      <set>
        <value>"Hello World"</value>
        <value>1.3</value>
        <ref id="myBean"/>
        <bean class="MyBean/>
      </set>
    </property>
  </bean>
</beans>

Links

  • Spring 3.1.x Reference – Section 4.4.2.4 Collections
  • mkyong‘s summary of the collection elements (actually nicer than my entry here :-))