Tutorials

Dependency Injection


Constructor Injection


When we inject dependency as a constructor argument through constructor at construction time then this type of dependency injection (DI) is known constructor injection.

The constructor-arg property inside bean element is used to inject the dependencies.

 

The constructor dependency  allows injecting following as the argument:

  • primitive or String values
  • objects
  • Collections

A simple example injecting primitive values as argument through constructor injection is explained below:

 

Java POJO - Subjects.java

package com.javaradar.constructorInjection;

public class Subjects {

  private String subjectName;
  private int subjectID;

  public Subjects(String subName, int subID){
   this.subjectName = subName;
   this.subjectID = subID;
  }

  public void displayDetails(){
   System.out.println("Subject Name:"+ subjectName);
   System.out.println("Subject Name:"+ subjectID);
 }
}

XML Configuration

Source File Name: applicationContext.XML
constructor injection spring by tutorialsinhand.com
 
 

Test Class: TestSubjects.java

package com.javaradar.constructorInjection;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

  public class TestSubjects {

    public static void main(String[] args) {
     ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
     Subjects subBean = (Subjects) context.getBean("SubjectsBean");
     subBean.displayDetails();

   }
}

	
OUTPUT:
Subject Name:Spring
Subject Name:1001
 

More details about the constructor injection is exaplained in the respective section of this spring tutorial.



Please Share this page
Views : 32