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.


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());



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

<beans xmlns="http://www.springframework.org/schema/beans"

	<bean id="department" class="com.jwt.spring.Department">
		<constructor-arg value="101"></constructor-arg>
		<constructor-arg value="Finance"></constructor-arg>
				<entry key="Manager" value="Amit"></entry>
				<entry key="Senior Manager" value="Ravi"></entry>
				<entry key="Director" value="Raj"></entry>



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(
		Department department = (Department) context.getBean("department");



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

comments powered by Disqus