Spring Constructor injection with Map

In Spring dependency injection is used to achieve loose coupling.
Let’s understand constructor dependency injection with map.

Project structure

Student.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
 
package com.spy.training;
 
import java.util.Iterator;
import java.util.List;
import java.util.Map;
 
public class Student 
{
	String name;
	Map<Integer, String> hobbies;
 
	public Student(String name,Map<Integer,String> hobbies)
	{
		this.name=name;
		this.hobbies=hobbies;
	}
 
	public String getName() 
	{
		return name;
	}
 
	public void setName(String name) 
	{
		this.name = name;
	}
	public Map<Integer, String> getHobbies() {
		return hobbies;
	}
	public void setHobbies(Map<Integer, String> hobbies) {
		this.hobbies = hobbies;
	}
 
	//User define method
	public void student_data()
	{
 
		System.out.println("Student name: "+name);
		//Retrieving List 
		System.out.println("***********");
 
		Iterator ie=hobbies.entrySet().iterator();
 
		while(ie.hasNext())
		{
			Map.Entry<Integer, String> s=(Map.Entry<Integer, String>)ie.next();
			System.out.println("id is: "+s.getKey());
			System.out.println("name is: "+s.getValue());	
		}
	}
}

Spring-config.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 
<?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="stu" class="com.spy.training.Student">  
 
 <constructor-arg type="java.lang.String" value="Bhavesh" />
 
 <constructor-arg>
 
 <map>
   <entry key="1" value="Bhavesh lakhani"></entry>  
 </map>
 
 </constructor-arg>
 
</bean>
 
</beans>

Testmain.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 
package com.spy.training;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class TestStudent 
{
	public static void main(String[] args) 
	{
                System.out.println("**********************");
 
		ApplicationContext context=new ClassPathXmlApplicationContext("Spring-config.xml");
	        Student s1=(Student)context.getBean("stu");
	        //calling student data
	        s1.student_data();
	        System.out.println("***********************");
	}
}

Output:

Leave a Reply

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