Home Tutorial Spring Spring3 Ioc Constructor Based Dependency Injection in Spring

 
 

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.

FirstBean.java 

package net.roseindia;

public class FirstBean {
  private AnotherBean another;

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

  public void display(String s) {
    another.anotherDisplay(s);
  }
}

AnotherBean.java

package net.roseindia;

public class AnotherBean {
  public void anotherDisplay(String s) {
    System.out.println(s);
  }
}

ReferenceMain.java

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(
        "context.xml");
    FirstBean bean = (FirstBeanbeanfactory.getBean("show");
    bean.display("hello spring");
  }
}

context.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
xmlns:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
>
<bean id="anotherBean" class="net.roseindia.AnotherBean" />
<bean id="show" class="net.roseindia.FirstBean">
<constructor-arg ref="anotherBean" />
</bean>
</beans>

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:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.