Tutorials

Constructor Injection


CI Object dependency


Invoking the object dependency is very important to understand as this is what you will be doing most of the time in real world projects.

We can easily pass an object or multiple objects as an argument in constructor to achieve the constructor injection

 

Given below is an example showing the way dependent object is injected using constructor injection.

 

Subjects.java
public class Subjects {

  private String subjectName;
  private int subjectID;

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

  //overriding toString()
  public String toString(){
  return subjectName+ " "+subjectID;
  }
}

 
Students.java
public class Student {
  private String name;
  private String stream;
  private Subjects subjects; //dependent object

  public Student(String name, String stream, Subjects subjects){
    this.name = name;
    this.stream = stream;
    this.subjects = subjects;
  }

  //display details
  public void displayStudentInfo(){
  System.out.println("Name :"+ name + "    "+ "Stream :"+ " " +stream);
  System.out.println("Subject details: "+ subjects);
  }
}

applicationContext.XML
 Object inject with CI by tutorialsinhand.com  
 
 

TestSpringClass.java

 

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

  public class TestSpringClass {

    public static void main(String[] args) { 

      ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

      Student student = (Student) context.getBean("studentbean");
      student.displayStudentInfo();
    }
}

		

OUTPUT:

Name :Rajneesh    Stream : Computer Science Engineering
Subject details: Spring 1001

 

 

 



Please Share this page
Views : 46
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!