Injecting Collections in Spring

Injecting Collections in Spring-We can inject collection values by constructor in spring framework. Spring Collections (List, Set, Map, and Properties) example. Spring examples to show you how to inject values into collections type (List, Set, Map, and Properties).
Injecting Collections in Spring

@ImageSource-SlideShare.net

You have seen how to configure primitive data type using value attribute and object references using ref attribute of the tag in your Bean configuration file(spring.xml). Both the cases deal with passing singular value to a bean. Now we will discuss about passing multiple value of data like List, Set, Collection, Map, Properties etc. To handle the situation, Spring offers four types of collection configuration element.

There are different tags are using by these different Collection elements as follows:
  • List  -- using-- <list> - </list>
  • Set   -- using-- <set> - </set>
  • Map -- using-- <map> - </map>
  • Properties --using-- <props> - </props>
1. Using List: Lets see that code snip sett how to use the List in the spring bean configuration file.
In this code snipset list contain all values tags only.
<property name="listOfShape">
   <list>
      <value>Triangle</value>
      <value>Circle</value>
      <value>Rectangle</value>
      <value>Square</value>
   </list>
</property>
In this code snipset list contain values and beans and inner bean tags.
<property name="listOfShape">
   <list>
      <value>Triangle</value>
      <value>Circle</value>
      <ref bean="rectangle"></ref>      
      <bean class="com.dineshonjava.sdnext.Square">
          <property name="width" value="20"></property>
      </bean>
    </list>
</property>
2. Using Set: Lets see that code snip sett how to use the Set in the spring bean configuration file.
In this code snipset set contain all values tags only.
<property name="setOfShape">
   <set>
      <value>Triangle</value>
      <value>Circle</value>
      <value>Rectangle</value>
      <value>Square</value>
   </set>
</property>
In this code snipset set contain values and beans and inner bean tags.
<property name="setOfShape">
   <set>
      <value>Triangle</value>
      <value>Circle</value>
      <ref bean="rectangle"></ref>      
      <bean class="com.dineshonjava.sdnext.Square">
          <property name="width" value="20"></property>
      </bean>
   </set>
</property>
3. Using Map: Lets see that code snip sett how to use the Map in the spring bean configuration file.
In this code snipset mapcontain all values tags only.
<property name="mapOfShape">
   <map>
     <entry key="1" value="Triangle">
     <entry key="2" value="Circle">
     <entry key="3" value="Rectangle">
     <entry key="4" value="Square">
     </entry></entry></entry></entry>
   </map>
</property>
In this code snipset map contain values and beans and inner bean tags.
<property name="mapOfShape">
   <map>
     <entry key="1" value="Triangle"></entry>
     <entry key="2" value="Circle"></entry>
     <entry key="3" value-ref="rectangle"></entry>
     <entry key="4">
        <bean class="com.dineshonjava.sdnext.Square">
          <property name="width" value="20"></property>
        </bean>
     </entry>
   </map>
</property>
4. Using Properties file: Lets see that code snip sett how to use the Properties file in the spring bean configuration file.
<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>
Now See the full example with the Value injecting to Collection.
ShapeCollection.java
package com.dineshonjava.sdnext.injectingCollection;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class ShapeCollection {
 private List<string>        shapeOfList;
 private Set<string>         shapeOfSet;
 private Map<string string=""> shapeOfMap;
 private Properties          shapeOfProperties;
 /**
  * @param shapeOfList the shapeOfList to set
  */
 public void setShapeOfList(List<string> shapeOfList) {
  this.shapeOfList = shapeOfList;
 }
 /**
  * @param shapeOfSet the shapeOfSet to set
  */
 public void setShapeOfSet(Set<string> shapeOfSet) {
  this.shapeOfSet = shapeOfSet;
 }
 /**
  * @param shapeOfMap the shapeOfMap to set
  */
 public void setShapeOfMap(Map<string string=""> shapeOfMap) {
  this.shapeOfMap = shapeOfMap;
 }
 /**
  * @param shapeOfProperties the shapeOfProperties to set
  */
 public void setShapeOfProperties(Properties shapeOfProperties) {
  this.shapeOfProperties = shapeOfProperties;
 }
 
 public String toString()
 {
return "List Elements :"  + shapeOfList+"\nSet Elements :"  + shapeOfSet+"\n" +
 "Map Elements :"  + shapeOfMap+"\nProperty Elements :"  + shapeOfProperties;
  
 }

}
Following is the configuration file spring.xml which has configuration for all the type of collections:
spring.xml
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   
   <bean class="com.dineshonjava.sdnext.injectingCollection.ShapeCollection" id="shapeCollection">

      
      <property name="shapeOfList">
        <list>
           <value>Triangle</value>
           <value>Circle</value>
           <value>Circle</value>
           <value>Rectangle</value>
        </list>
      </property>

     
     <property name="shapeOfSet">
        <set>
           <value>Triangle</value>
           <value>Circle</value>
           <value>Circle</value>
           <value>Rectangle</value>
        </set>
      </property>

     
     <property name="shapeOfMap">
        <map>
           <entry key="1" value="Triangle">
           <entry key="2" value="Circle">
           <entry key="3" value="Circle">
           <entry key="4" value="Rectangle">
        </entry></entry></entry></entry></map>
      </property>

     
     <property name="shapeOfProperties">
        <props>  
      <prop key="triangle">Triangle</prop>  
      <prop key="circle1">Circle</prop>  
      <prop key="circle2">Circle</prop>  
      <prop key="rectangle">Rectangle</prop>  
    </props> 
      </property>

   </bean>

</beans>
DrawingApp.java
package com.dineshonjava.sdnext.injectingCollection.tutorial;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.dineshonjava.sdnext.injectingCollection.ShapeCollection;


/**
 * @author Dinesh Rajput
 *
 */
public class DrawingApp 
{
 /**
  * @param args
  */
 public static void main(String[] args) 
 {
  ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
  ShapeCollection shapeCollection = (ShapeCollection) context.getBean("shapeCollection");
  System.out.println(shapeCollection);
 }
}
Once you are done with creating source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message on console:
Output:
Jun 24, 2012 3:50:42 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@ab50cd: startup date [Sun Jun 24 15:50:42 IST 2012]; root of context hierarchy
Jun 24, 2012 3:50:42 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Jun 24, 2012 3:50:43 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1fc2fb: defining beans [shapeCollection]; root of factory hierarchy
List Elements :[Triangle, Circle, Circle, Rectangle]
Set Elements :[Triangle, Circle, Rectangle]
Map Elements :{1=Triangle, 2=Circle, 3=Circle, 4=Rectangle}
Property Elements :{rectangle=Rectangle, circle2=Circle, triangle=Triangle, circle1=Circle}

Injecting Bean References to the Collection:
In the following bean configuration file has understand how to inject bean references as one of the collection's element.

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean class="com.dineshonjava.sdnext.injectCollection.Triangle" id="triangle">
       <property name="height" value="30"></property>
       <property name="type" value="Eqiletral"></property>
   </bean>

   <bean class="com.dineshonjava.sdnext.injectingCollection.ShapeCollection" id="shapeCollection">

     
      <property name="shapeOfList">
        <list>
           <value>Circle</value>
           <value>Circle</value>
           <ref bean="triangle"></ref>
           <bean class="com.dineshonjava.sdnext.injectCollection.Rectangle">
              <property name="height" value="30"></property>
              <property name="width" value="50"></property>
           </bean>
        </list>
      </property>

     
     <property name="shapeOfSet">
        <set>
           <value>Circle</value>
           <value>Circle</value>
           <ref bean="triangle"></ref>
           <bean class="com.dineshonjava.sdnext.injectCollection.Rectangle">
              <property name="height" value="30"></property>
              <property name="width" value="50"></property>
           </bean>
        </set>
      </property>

     
     <property name="shapeOfMap">
        <map>
           <entry key="2" value="Circle"></entry>
           <entry key="3" value="Circle"></entry>
           <entry key="1" ref-value="triangle"></entry>
           <entry key="4">
              <bean class="com.dineshonjava.sdnext.injectCollection.Rectangle">
                 <property name="height" value="30"></property>
                 <property name="width" value="50"></property>
               </bean>
           </entry>
        </map>
      </property>

     
     <property name="shapeOfProperties">
        <props>  
          <prop key="triangle">Triangle</prop>  
          <prop key="circle1">Circle</prop>  
          <prop key="circle2">Circle</prop>  
          <prop key="rectangle">Rectangle</prop>  
        </props> 
      </property>

   </bean>

</beans>
Spring Related Topics you may like
  1. Spring Interview Questions and Answers
  2. Spring AOP Interview Questions and Answers
  3. Spring MVC Interview Questions
  4. Spring Security Interview Questions and Answers
  5. Spring REST Interview Questions and Answers
  6. Spring Boot Interview Questions and Answers
  7. Spring Boot Microservices Interview Questions and Answers
  8. Dependency Injection (DI) in Spring
  9. Spring IoC Container
  10. What is Bean Factory in Spring
  11. ApplicationContext in Spring
  12. Bean Autowiring in Spring
  13. Spring Bean Scopes
  14. Create Custom Bean Scope in Spring Example
  15. Using ApplicationContextAware in Spring
  16. Spring Bean Life Cycle and Callbacks
  17. BeanPostProcessor in Spring
  18. BeanFactoryPostProcessor in Spring
  19. Annotations in Spring and Based Configuration
  20. Spring JSR-250 Annotations
  21. JSR 330 Annotations in Spring
  22. Spring @Component, @Repository, @Service and @Controller Stereotype Annotations
  23. Method injection with Spring using Lookup method property
  24. Spring AOP-Introduction to Aspect Oriented Programming
  25. @Aspect Annotation in Spring
  26. Spring AOP AspectJ @Before Annotation Advice Example
  27. Spring AOP Before Advice Example using XML Config
  28. Spring AOP AspectJ @After Annotation Advice Example
  29. Spring AOP After Advice Example using XML Config
  30. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  31. Spring AOP After-Returning Advice Example using XML Config
  32. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  33. Spring AOP After Throwing Advice Example using XML Config
  34. Spring AOP AspectJ @Around Annotation Advice Example
  35. Spring AOP Around Advice Example using XML Config
  36. Spring AOP Proxies in Spring
  37. Spring AOP Transaction Management in Hibernate
  38. Spring Transaction Management
  39. Spring Declarative Transaction Management Example
  40. Spring AOP-Ordering of Aspects with Example
  41. Spring Security Java Based Configuration with Example
  42. Spring Security XML Namespace Configuration Example

In Next Chapter we will discuss about Beans Auto Wiring in Spring with Example in Application.
                                          
                                                        << Previous || Next >>



Labels: