Categories
Spring Spring Core

Collection as Dependency Injection

As like Primitives and User Defined classes we can provide Collections as Dependencies in Spring Framework. 

We will look at Collections as Dependencies in Spring with Constructor and Setter Injection in a Simple working example.

In the below example I included all the possible Collections with Static and Dynamic values. 

Before walkin to the Example code we shall look at each Collection Types with Java Equivalent. This will make you understand the example even better.

I’m trying to make this example as simple as possible for readability. 

List & Set

<list>
    <value>Value at Index 1</value>
    <value>Value at Index 2</value>
    <value>Value at Index 3</value>
</list>

Equivalent to :

list.add(“Value at Index 1”);
list.add(“Value at Index 2”);
list.add(“Value at Index 3”);

The above coding snippet is for Hardcoded values. We can also add an dynamically created Object from Configuration Meta-Data.

<set>
	<ref bean=”employee”></ref>
</set>

The above code will refer to the employee bean and pass it as one of the parameters to Setter or Constructor as per the request.You can provide a ref bean to List and Static values to Set.

Properties

<property name="properties">
	<props>
		<prop key="emailID">contact@geekcoders.net</prop>
		<prop key="address">Online</prop>
	</props>
</property>

The above code is equivalent to .property file data as below.

emailID : contact@geekcoders.net
address : Online

Or a Java code

properties.setProperty(“emailID”, “contact@geekcoders.net”);
properties.setProperty(“address”,”Online”);

You can provide ref bean instead of Static values as like List implementation in this example.

Map

<property name="map">
	<map>
		<entry key="EmployeeDetails" value-ref="employee"></entry>
	</map>
</property>

Equivalent to : 

map.put(“EmployeeDetails”,employee);

As like List and Properties you can provide Hard Coded values for Map implementation.

Now we Step-in to the example code :

Step 1 : Controller Class

Create a class under “net.geekcoders.controllers” package and name it as “SpringCollectionController” and copy the code below.

package net.geekcoders.controllers;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import net.geekcoders.Employee;
public class SpringCollectionController {
	private Properties properties;
	private List<String> list;
	private Set<Employee> set;
	private Map<String,Employee> map;
	
	public SpringCollectionController(List<String> list,Set<Employee> set) {
		this.setList(list);
		this.setSet(set);
		this.setProperties(properties);
		this.setMap(map);
	}
	
	public Properties getProperties() {
		System.out.println("Properties :"+properties.toString());
		return properties;
	}
	public void setProperties(Properties properties) {
		this.properties = properties;
	}
	public List<String> getList() {
		System.out.println("List :"+list.toString());
		return list;
	}
	public void setList(List<String> list) {
		this.list = list;
	}
	public Set<Employee> getSet() {
		System.out.println("Set :"+set.toString());
		return set;
	}
	public void setSet(Set<Employee> set) {
		this.set = set;
	}
	public Map<String,Employee> getMap() {
		System.out.println("Map :"+map.toString());
		return map;
	}
	public void setMap(Map<String,Employee> map) {
		this.map = map;
	}
}

I have used Constructor Injection for List and Set and Setter Injection for Properties and Map implementations.

Employee Class is used to store Employee Details and this object will be manipulated by Controller Class on request.

Step 2 : Employee Class

Create a Class named Employee under “net.geekcoders” package and copy the below code.

package net.geekcoders;
public class Employee {
private String empName;
private String empRole;
public String getEmpName() {
	return empName;
}
public void setEmpName(String empName) {
	this.empName = empName;
}
public String getEmpRole() {
	return empRole;
}
public void setEmpRole(String empRole) {
	this.empRole = empRole;
}
}

The above class has two fields and getters, setters. IoC will inject values in the form of Setter Injection.

Step 3 : Configuration Meta-Data

Create applicationContext.xml file under the src folder of your project and provide Bean Definition for Controller and its Dependency Employee Object.

<?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="springCollectionController"
		class="net.geekcoders.controllers.SpringCollectionController">
		<constructor-arg>
			<list>
				<value>Value at Index 1</value>
				<value>Value at Index 2</value>
				<value>Value at Index 3</value>
			</list>
		</constructor-arg>
		
		<constructor-arg>
			<set>
				<ref bean="employee"></ref>
			</set>
		</constructor-arg>
		
		<property name="properties">
			<props>
				<prop key="emailID">contact@geekcoders.net</prop>
				<prop key="address">Online</prop>
			</props>
		</property>
		
		<property name="map">
			<map>
				<entry key="EmployeeDetails" value-ref="employee"></entry>
			</map>
		</property>
	</bean>
	
	<bean id="employee" class="net.geekcoders.Employee">
		<property name="empName" value="Murug"></property>
		<property name="empRole" value="Developer"></property>
	</bean>
</beans>

Here we have used all the available collection implementations in a single Controller. In real time projects you will use Map and List implementations in most of the cases. All the Collection manipulations will be handled within Controller and its helper classes itself. This example is for your knowledge on Collection implementation in Spring. 

Step 4 : IoC Container

To make this example code running we have to Create IoC container and provide Configuration Meta-Data to it. 

As it is a Spring-Core application, I’m creating IoC in a Class with the main method in it.

package net.geekcoders.controllers;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringCollectionStarter {
	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
		SpringCollectionController springCollectionController = applicationContext.getBean("springCollectionController",SpringCollectionController.class);
		springCollectionController.getList();
		springCollectionController.getSet();
		springCollectionController.getProperties();
		springCollectionController.getMap();
	}
}
  • IoC Container will read the Meta-Data and create an Instance of SpringCollectionController and Employee objects.
  • All the Dependencies of the Controller class will get set in the form of Constructor args and Setter parameter.
  • Create an Instance of SpringCollectionController and call the required methods to know whether it is working fine.

(To know more on Bean creation from IoC Container and its working model please refer to these articles).

If you run the above SpringCollectionStarter class you can see the below output printed in Console.

As you see the above output, we successfully passed required parameters to List, Set, Properties and Map implementations and it is working fine.

That’s all for now on Collection as Dependency in Spring article.

Happy Reading!!!

Leave a Reply

Your email address will not be published. Required fields are marked *