Share on Google+Share on Google+

Constructor Based Dependency Injection in Spring

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;

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


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