Home Tutorial Spring Spring3 Ioc Constructor Based Dependency Injection in Spring


Share on Google+Share on Google+
Constructor Based Dependency Injection in Spring
Posted on: August 11, 2010 at 12:00 AM
In this tutorial you will learn about the Constructor-based dependency injection in spring framework.

Constructor-based dependency injection

In the constructor-based dependency injection one bean definition is injected to another. For this  you use the constructor-arg or property's ref attribute instead of the value attribute.

In this example, you will see a bean definition is injected to another bean. The first bean definition is the FirstBean with the id firstBean. It is injected into the another bean definition by reference using the property element's ref attribute.


package net.roseindia;

public class FirstBean {
  private AnotherBean another;

  public FirstBean(AnotherBean another) {
    this.another = another;

  public void display(String s) {


package net.roseindia;

public class AnotherBean {
  public void anotherDisplay(String s) {


package net.roseindia;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ReferenceMain {
  public static void main(String[] args) {
    BeanFactory beanfactory = new ClassPathXmlApplicationContext(
    FirstBean bean = (FirstBeanbeanfactory.getBean("show");
    bean.display("hello spring");


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
<bean id="anotherBean" class="net.roseindia.AnotherBean" />
<bean id="show" class="net.roseindia.FirstBean">
<constructor-arg ref="anotherBean" />

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

Hello Spring

Download this example code


Related Tags for Constructor Based Dependency Injection in Spring:

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: August 11, 2010

Recommend the tutorial

Advertisements Advertisements