Share on Google+Share on Google+

Spring Constructor Injection Example

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; = 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=""

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

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


Posted on: November 9, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial 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.