Tutorials

Setter Injection


Injecting Collection Set


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

Taking setter injection approach, collection values can be injected using the <properties> element in XML configuration file.

 

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

 

Java POJO - Department.java

import java.util.Iterator;
import java.util.Set;

public class Department {

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

	public String getDept() {
		return dept;
	}

	public void setDept(String dept) {
		this.dept = dept;
	}

	public int getDeptId() {
		return deptId;
	}

	public void setDeptId(int deptId) {
		this.deptId = deptId;
	}

	public Set<String> getSubjects() {
		return subjects;
	}

	public void setSubjects(Set<String> subjects) {
		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 - appContext.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="Department">  
<property name="dept" value="Computer Science Engineering"></property>
<property name="deptId" value="1004"></property>
<property name="subjects">
<set>
<value>Java</value>
<value>Spring</value>
<value>C</value>
<value>ANSI SQL</value>
<value>Java</value>
<value>C</value>
</set>
</property>
</bean>

</beans>

Test

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

public class TestSpringClass {

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

}

OUTPUT:

Department: Computer Science Engineering
Department Id: 1004
::Subjects to study::
Java
Spring
C
ANSI SQL
 

 

 



Please Share this page
Views : 52
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!