Home Tutorial Spring Spring Constructor Injection Example


Share on Google+Share on Google+
Spring Constructor Injection Example
Posted on: November 9, 2011 at 12:00 AM
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


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;		

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



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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" />


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(
		StudentBean studentBean = (StudentBean) context.getBean("student");

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

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

Download Select Source Code


Related Tags for Spring Constructor Injection Example:

Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: November 9, 2011

Recommend the tutorial

Advertisements Advertisements