Home » Spring » Spring Constructor Injection with Map

Spring Constructor Injection with Map

In this example we will discuss about constructor injection with map by using a simple and self explanatory program.Here, We are using key and value pair both as a string. Like previous examples, it is the example of department where one Department can have multiple Employee.

Department.java

package com.jwt.spring;
import java.util.Map;
public class Department {
	private int departmentId;
	private String departmentName;
	private Map<String, String> employee;
	public Department(int departmentId, String departmentName,
			Map<String, String> employee) {
		this.departmentId = departmentId;
		this.departmentName = departmentName;
		this.employee = employee;
	}
	public void displayResult() {
		System.out.println("Department id is : " + departmentId);
		System.out.println("Department Name is : " + departmentName);
		System.out.println("Employee Details....");
		for (Map.Entry me : employee.entrySet()) {
			System.out.println("Employee Designation :" + me.getKey() + ", Name:"
					+ me.getValue());
		}
	}
}

bean.xml

The entry attribute of map is used to define the key and value information.

<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
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
	<bean id="department" class="com.jwt.spring.Department">
		<constructor-arg value="101"></constructor-arg>
		<constructor-arg value="Finance"></constructor-arg>
		<constructor-arg>
			<map>
				<entry key="Manager" value="Amit"></entry>
				<entry key="Senior Manager" value="Ravi"></entry>
				<entry key="Director" value="Raj"></entry>
			</map>
		</constructor-arg>
	</bean>
</beans>

Test.java

This class gets the bean from the applicationContext.xml file and calls the displayResult() method of Department bean class.

package com.jwt.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"bean.xml");
		Department department = (Department) context.getBean("department");
		department.displayResult();
	}
}
Output:
Department id is : 101
Department Name is : Finance
Employee Details....
Employee Designation :Manager, Name:Amit
Employee Designation :Senior Manager, Name:Ravi
Employee Designation :Director, Name:Raj



Previous Next Article
comments powered by Disqus