How to Inject Collection using Dependency Injection in Spring

In the previous article, we have seen How to inject Composition(HAS-A relationship) using the constructor and setter method you can check it here How to use Has-A relationship using Dependency Injection?. In this article, we will see How we can inject collection using Dependency Injection in Spring.

As we know, In java we have a Collection Framework which makes the thing easy for us to iterate over an object or to perform operations on a group of objects.

In Spring Framework, we will inject the Collection type by constructor or setter method using elements such as :

Elements
Description
<list> It injects a list of values. It allows duplicates.
<set> It injects a set of values. It allows only unique value
<map> It injects values in key-value pairs.
<props> It injects values in key-value pairs where key & value both are strings.

Let us take an example of to Injects List Collection type using Dependency Injection using Constructor Injection.

Example of Injecting Collection Type List using Constructor Injection

Here, we will be Creating a Class Category that has multiple products. Following are the files you have to create:

  • Category.java
  • beans.xml
  • App.java

Create a Spring Project Go to File> New > Other > Search maven > Select Maven Project > Next > Search Filter org.apche.maven.archetypes/webapp > Next > Enter Group Id & Archetype id > Finish.

  • Create a class category with id, name attribute, and list of product attributes with the constructor.

Category.java

package com.codedec.di;

import java.util.List;

public class Category {

  private String categoryId;
  private String categoryName;
  private List<String> products;

  public Category(String categoryId, String categoryName, List<String> products) {
    this.categoryId = categoryId;
    this.categoryName = categoryName;
    this.products = products;
  }

  public void show() {
    System.out.println("Category Id : :" + categoryId + "Category Name:: " + categoryName);
    System.out.println("List of products :");
    for (String items : products) {
      System.out.println( items);
    }
  }
}
  • Create a beans.xml file with <constructor-arg> element.
  • The <list> element is used to define the list of elements.

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="category" class="com.codedec.di.Category">
    <constructor-arg value="101"></constructor-arg>
    <constructor-arg value="Shoes"></constructor-arg>
    <constructor-arg>
      <list>
        <value>Nike</value>
        <value>Adidas</value>
        <value>Puma</value>
      </list>
    </constructor-arg>

  </bean>
</beans>
  • Create an App.java and create the object of Application Context, get the bean from it and call the show() method.

App.java

package com.codedec.di;

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

public class App {

  public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    Category c1 = context.getBean("category", Category.class);
    c1.show();
  }

}

Output

Category Id : :101Category Name:: Shoes
List of products :
Nike
Adidas
Puma

In this way, we inject the collection type List using constructor injection.

Example of Injecting Collection Type List using setter method Injection.

Here, we will be Creating a Class Category that has multiple products. Following are the files you have to create:

  • Category.java
  • beans.xml
  • App.java

Create a Spring Project Go to File> New > Other > Search maven > Select Maven Project > Next > Search Filter org.apche.maven.archetypes/webapp > Next > Enter Group Id & Archetype id > Finish.

  • Create a class Category class with Id, name, and list of a product attribute with a setter method.

Category.java

package com.codedec.di;

import java.util.List;

public class Category {

  private String categoryId;
  private String categoryName;
  private List<String> products;

  public String getCategoryId() {
    return categoryId;
  }

  public void setCategoryId(String categoryId) {
    this.categoryId = categoryId;
  }

  public String getCategoryName() {
    return categoryName;
  }

  public void setCategoryName(String categoryName) {
    this.categoryName = categoryName;
  }

  public List<String> getProducts() {
    return products;
  }

  public void setProducts(List<String> products) {
    this.products = products;
  }

  public void show() {
    System.out.println("Category Id : :" + categoryId + "Category Name:: " + categoryName);
    System.out.println("List of products :");
    for (String items : products) {
      System.out.println(items);
    }
  }
}
  • Create a beans.xml file with <property> element.
  • The <property> element would invoke the setter method of the class specified in <bean> element.

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="category" class="com.codedec.di.Category">
    <property name="categoryId" value="105"></property>
    <property name="categoryName" value="Watch"></property>
    <property name="products">
      <list>
        <value>Titan</value>
        <value>Fastrack</value>
        <value>Louis Moinet</value>
      </list>
    </property>
  </bean>
</beans>
  • Create an App.java and create the object of the Application context, get the bean from it, and call the show() method.

App.java

package com.codedec.di;

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

public class App {

  public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    Category c1 = context.getBean("category", Category.class);
    c1.show();
  }

}

Output

Category Id : :105Category Name:: Watch
List of products :
Titan
Fastrack
Louis Moinet

In this way, we inject the collection type List using the Setter Method Injection.

Now, we will look at another example where we will use the Collection type called Map which has values in Key-value pair format.

Example of Injecting Collection Type Map using Constructor Injection

Here, we will be Creating a Class Country that has multiple cities. Following are the files you have to create:

  • Country.java
  • beans.xml
  • App.java

Create a Spring Project Go to File> New > Other > Search maven > Select Maven Project > Next > Search Filter org.apche.maven.archetypes/webapp > Next > Enter Group Id & Archetype id > Finish.

  • Create a class Country with location, name attribute, and Map of capital City attributes with the constructor.
  • Here, we have used the Map Collection type to store cities with their capital.
  • We have used for loop to Iterate over both keys and value.

Country.java

package com.codedec.di;

import java.util.Map;

public class Country {

  private String location;
  private String countryName;
  private Map<String, String> capital;

  public Country(String location, String countryName, Map<String, String> capital) {
    this.location = location;
    this.countryName = countryName;
    this.capital = capital;
  }

  public void show() {
    System.out.println("Country Location ::" + location + " Country Name :: " + countryName);
    // Iterate value of Map
    for (Map.Entry<String, String> entry : capital.entrySet()) {
      System.out.println("Key = " + entry.getKey() + ", Value =" + entry.getValue());

    }
  }

}
  • Create a beans.xml file with <constructor-arg> element.
  • The <map> element is used to define the Collection type Map.

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="country" class="com.codedec.di.Country">
    <constructor-arg value="Asia"></constructor-arg>
    <constructor-arg value="India"></constructor-arg>
    <constructor-arg>
      <map>
        <entry key="Maharashtra" value="Mumbai"></entry>
        <entry key="UP" value="Lucknow"></entry>
        <entry key="Orissa" value="Bhubaneshwar"></entry>

      </map>
    </constructor-arg>

  </bean>
</beans>
  • Create an App.java and create the object of Application Context, get the bean from it and call the show() method.

App.java

package com.codedec.di;

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

public class App {

  public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    Country c1 = context.getBean("country", Country.class);
    c1.show();
  }

}

Output

Country Location ::Asia Country Name :: India
Key = Maharashtra, Value =Mumbai
Key = UP, Value =Lucknow
Key = Orissa, Value =Bhubaneshwar

In this way, we inject the collection type Map using constructor injection.

Example of Injecting Collection Type Map using setter method Injection.

Here, we will be Creating a Class Country that has multiple cities. Following are the files you have to create:

  • Country.java
  • beans.xml
  • App.java

Create a Spring Project Go to File> New > Other > Search maven > Select Maven Project > Next > Search Filter org.apche.maven.archetypes/webapp > Next > Enter Group Id & Archetype id > Finish.

  • Create a Country Class with location, name, and Map of Capital city attribute with Setter methods.
  • Here, we have used the Map Collection type to store cities with their capital.
  • We have used for loop to Iterate over both keys and value.

Country.java

package com.codedec.di;

import java.util.Map;

public class Country {

  private String location;
  private String countryName;
  private Map<String, String> capital;

  public String getLocation() {
    return location;
  }

  public void setLocation(String location) {
    this.location = location;
  }

  public String getCountryName() {
    return countryName;
  }

  public void setCountryName(String countryName) {
    this.countryName = countryName;
  }

  public Map<String, String> getCapital() {
    return capital;
  }

  public void setCapital(Map<String, String> capital) {
    this.capital = capital;
  }

  public void show() {
    System.out.println("Country Location ::" + location + " Country Name :: " + countryName);
    // Iterate value of Map
    for (Map.Entry<String, String> entry : capital.entrySet()) {
      System.out.println("Key = " + entry.getKey() + ", Value =" + entry.getValue());

    }
  }

}
  • Create a beans.xml file with <property> element.
  • The <map> element is used to define the Collection type Map.
  • The <property> element would invoke the setter method in the Country class.

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="country" class="com.codedec.di.Country">
    <property name="location" value="Asia"></property>
    <property name="countryName" value="India"></property>
    <property name="capital">
      <map>
        <entry key="Maharashtra" value="Mumbai"></entry>
        <entry key="UP" value="Lucknow"></entry>
        <entry key="Orissa" value="Bhubaneshwar"></entry>

      </map>
    </property>

  </bean>
</beans>
  • Create an App.java and create the object of Application Context, get the bean from it and call the show() method.

App.java

package com.codedec.di;

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

public class App {

  public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    Country c1 = context.getBean("country", Country.class);
    c1.show();
  }

}

Output

Country Location ::Asia Country Name :: India
Key = Maharashtra, Value =Mumbai
Key = UP, Value =Lucknow
Key = Orissa, Value =Bhubaneshwar

In this way, we inject the collection type Map using Setter Method Injection.

Thus, in this article, we have learned How to Inject Collection types in Spring Framework with the help of Constructor and Setter Method Injection.