Injecting Collection in Spring(Dependency Injection in the form of Collection)

In my previous article we have already learnt about the Dependency Injection in Spring and Setter Injection in the form of Primitives and injection in the form of Objects.


Before collection, we used to pass single value at a time. If we are required to pass multiple or bundle of data to be passed like List, Set, and Map etc. To manage such kind or problem, spring provides a way of injecting collections. We can inject list, map, set and pros type collections in spring.There are separate tags are used for these type of collection types as listed below.

  • List- By using <list> - </list> element.
  • Set- By using <set> - </set> element.
  • Map- By using <map> - </map> element.
  • Properties- By using <props> - </props> element.


In my previous article we have already learnt about the Dependency Injection in Spring and Setter Injection in the form of Primitives and injection in the form of Objects.

Before collection, we used to pass single value at a time. If we are required to pass multiple or bundle of data to be passed like List, Set, and Map etc. To manage such kind or problem, spring provides a way of injecting collections. We can inject list, map, set and pros type collections in spring.There are separate tags are used for these type of collection types as listed below.

  • List- By using <list> - </list> element.
  • Set- By using <set> - </set> element.
  • Map- By using <map> - </map> element.
  • Properties- By using <props> - </props> element.




Using List

Below is the code snippet to use the List in the spring bean configuration file. In this code snippet list contains values tags only.

<property name="employeeList">
   <list>
      <value>Name</value>
      <value>Department</value>
      <value>Email</value>
      <value>Phone</value>
   </list>
</property>


Using Set

Below is the code snippet to use the Set in the spring bean configuration file. In this code snippet set contains values tags only.

<property name="employeeSet">
   <set>
      <value>Name</value>
      <value>Department</value>
      <value>Email</value>
      <value>Phone</value>
   </set>
</property>


Using Map

Below is the code snippet to use the Map in the spring bean configuration file. In this code snippet Map contains values tags only.

<property name="employeeMap">
   <map>
     <entry key="1" value="Name">
     <entry key="2" value="Department">
     <entry key="3" value="Email">
     <entry key="4" value="Phone">
   </map>
</property>



Using Properties file

Below is the code snippet to use the properties in the spring bean configuration file. In this code snippet properties contains values tags only.

<property name="proprtyOfShape">
   <props>
     <prop key="triangle">Triangle</prop>
     <prop key="circle">Circle</prop>
     <prop key="rectangle">Rectangle</prop>
     <prop key="sqare">Square</prop>
   </props>
</property>






comments powered by Disqus