Spring Constructor injection Example

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
53
54
55
56
57
58
59
package com.spy.training;
 
import java.util.List;
 
public class Student 
{
 
	String name;
 
	List<String> hobbies;
 
	public Student(String name,List hobbies)
	{
 
		this.name=name;
		this.hobbies=hobbies;
 
	}
 
	public String getName() 
	{
		return name;
	}
 
	public void setName(String name) 
	{
		this.name = name;
	}
 
	public List<String> getHobbies() 
	{
		return hobbies;
	}
 
	public void setHobbies(List<String> hobbies) 
	{
		this.hobbies = hobbies;
	}
 
 
 
	//User define method
	public void student_data()
	{
 
		System.out.println("Student name: "+name);
 
		//Retrieving List 
		System.out.println("***Hobbies ***");
		for(int i=0;i<hobbies.size();i++)
		{
 
			System.out.println(hobbies.get(i));
 
		}
 
	}
 
}

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
25
<?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>
 
	 <list>
		 <value>Playing Cricket</value>
		 <value>Traveling</value>
	 </list>
 
 </constructor-arg>
 
</bean>
 
 
</beans>

TestStudent.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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 *