Tutorials

Constructor Injection


Injecting Collection Set


In the last chapter of this tutorial, we have learned about injecting collection list dependency using constructor injection.

Taking constructor injection approach, collection values can be injected in the <constructor-arg> element in XML configuration file.

 

In this chapter of the spring tutorial we will inject set as dependency.

 

Java POJO - Department.java

//Code by tutorialsinhand.com
package com.javaradar.constructorInjection;

import java.util.Iterator;
import java.util.List;

public class Department {

	private String dept;
	private int deptId;
	private List<String> subjects;

	public Department(String dept,int deptId, List<String> subjects){
		this.dept = dept;
		this.deptId = deptId;
		this.subjects = subjects;
	}

	public void displayDetails(){
		System.out.println("Department: "+ dept);
		System.out.println("Department Id: "+ deptId);

		Iterator<String> deptItr = subjects.iterator();

		System.out.println("::Subjects to study::");
		while(deptItr.hasNext()){			
			System.out.println(deptItr.next());
		}
	}
}

XML Configuration - applicationContext.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"  
    xmlns:p="http://www.springframework.org/schema/p"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
               http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  


<bean id="departmentBean" class="com.javaradar.constructorInjection.Department">  
<constructor-arg value="Computer Science Engineering"></constructor-arg>
<constructor-arg value="1004"></constructor-arg>
<constructor-arg>
<set>
<value>Java</value>
<value>Spring</value>
<value>C</value>
<value>ANSI SQL</value>
<value>Java</value>
<value>C</value>
</set>
</constructor-arg>
</bean>

</beans>

Test Class

package com.javaradar.constructorInjection;

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

public class TestDepartment {

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		Department subBean = (Department) context.getBean("departmentBean");
		subBean.displayDetails();
		
	}

}

OUTPUT

Department: Computer Science Engineering

Department Id: 1004

::Subjects to study::

Java

Spring

C

ANSI SQL

 

As we know that set stores only unique elements so the duplicate elements (Java and C) are not printed that was provided through xml configuration file.

 

 

 



Please Share this page
Views : 57
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!