Spring Constructor Injection Example


 

Spring Constructor Injection Example

In this tutorial you will learn about learn about Constructor Injection

In this tutorial you will learn about learn about Constructor Injection

Spring Constructor Injection Example

In Spring Framework the constructor injection is also a type of Dependency injection (like Setter Injection).  An Example of Constructor Injection is given below

StudentBean.java

package net.roseindia;

public class StudentBean {
	private String name;
	private int rollNo;
	private String course;

	public StudentBean(int rollNo, String name, String course) {
		this.rollNo = rollNo;
		this.name = name;
		this.course = course;		
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "Roll No- " + rollNo + "\nName- " + name + "\nCourse- " + course
				+ "\n";

	}
}

bean.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="student" class="net.roseindia.StudentBean">
<constructor-arg index="0" type="int" value="001" />
<constructor-arg index="1" type="java.lang.String"
value="John" />
<constructor-arg index="2" type="java.lang.String"
value="B.Tech" />
</bean>
</beans>

MainClaz.java

package net.roseindia;

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

public class MainClaz {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"bean.xml");
		StudentBean studentBean = (StudentBean) context.getBean("student");
		System.out.println(studentBean);
	}
}


When you run this application it will display message as shown below:


Roll No- 1
Name- John
Course- B.Tech

Download Select Source Code

Ads