Spring Constructor Injection

Dependency Injection is the main functionality of the Spring IoC(Inversion of Control) container. Spring IoC container injects the spring bean class(Dependent class) into another spring class(Target class) through dependency injection.
Constructor Injection:
   • It is one of the kinds of Dependency Injection.
   • Constructor Injection(Spring Container uses the parameterized constructor to create spring bean class object value to that object).  

Dependent Class:

class Dependent{

----------------

-----------------

}

Target Class:

class Target {

----------------

-----------------

}

Sample of XML config file Spring bean classes:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Dependent class configure here-->
<bean id="bean_id_name" class="package_name" />
<!--Target  class configure here-->
<bean id="bean_id_name" class="package_name" />
<!-- set up constructor injection -->
<constructor-arg value="assign_value"/>
<constructor-arg ref="spring_bean_referece_name"/>
</bean>
</beans>

In this project, we will create three classes. The first POJO class we will create for the Dependent class, the Second POJO class we will create for the Target class and the Third POJO class we will create for the main class so that project run to read this class which is containing the main method. We will create one XML configuration file for the Spring Bean class configuration. 
In the first class, we will create a 0-parameter constructor which contains a simple print as a message to analyze first this 0-parameter constructor is executed and also a method to print some message. Finally, we can confirm the class when it is instantiated properly and access the defined method of it.


In the second class, we will create a parameterized constructor which will pass the parameter of the first class type reference and simply print as a message. So, the Spring Container will use to inject the first POJO class into the second POJO  class with this parameterized constructor. So in this class parameterized constructor will be executed when it is instantiated.
In the XML configuration file, we can define these classes as Spring Bean and configure constructor injection.
In the main class, we will activate Spring Container, and load and read the XML configuration file. We will get the Spring bean class from the Spring container. So we will access the Spring bean class’s method configured in the XML configuration file. Then we will get the output of this project on the console view.


In this project, we analyse to configure Spring Bean constructor injection in the XML configuration in a very easy manner. In this example, we are injecting a dependent class into the target class through Constructor Injection. The CricketCoach POJO class is a dependent class and CricketTeam POJO class is a target class. These classes are configured as the Spring Beans in the XML configuration file. So the Spring IoC container injects the CricketCoach Spring bean class to the CricketTeam Spring bean class through the parameterized of the CricketTeam  Spring bean class. 

Development Process:
    1. Keep eclipse IDE ready
    2. Project Structure
    3. Create a  Dependent Bean Class
    4. Create a  Target Bean Class
    5. Configure your Spring Beans
    6. Add the jar file to the Build Path of the Project for the example of the constructor injection with XML configuration
    7. Run the App

1. Keep eclipse IDE ready
2. Project Structure

constructor_injection_xml_config

3. Create a Dependent Bean Class
CricketCoach.java(Pojo Class):

package com.poc.bean;

public class CricketCoach {

  public CricketCoach() {

 System.out.println("Constructor: 0-param constructor call of CricketCoach");

  }

  public String getDailyWorkout() {

    return "6 hours of practice";

  }

}

4. Create a Target Bean Class
CricketTeam.java(Pojo class):

package com.poc.bean;

public class CricketTeam {
private String name;
//dependent class
private CricketCoach teamCoach;

  public CricketTeam(String name, CricketCoach coach) {

System.out.println("Constructor: parameterized constructor is called CricketTeam");
     this.name = name;
    this.teamCoach = coach;

  }

  public String getInstruction() {

return "Team Name: " + name + "----" + teamCoach.getDailyWorkout();

  }
}

→ Spring IoC container injects CricketCoach spring bean class to the CricketTeam spring bean class through CricketTeam(-) parameterized constructor.

5. Configure your Spring Beans
applicationContext.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"

xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
	<!--Define your beans here-->
	<!-- Define dependent bean -->
	<bean id="myCoach" class="com.poc.bean.CricketCoach" />
	<bean id="team" class="com.poc.bean.CricketTeam">
		<!-- set up constructor injection -->
		<constructor-arg value="Mumbai Indians"/>
		<constructor-arg ref="myCoach"/>
	</bean>
</beans>

→ <constructor-arg>tag is used to configure bean property for constructor injection.
→ In the above configuration, the spring container creates the “CricketCoach” class object using a 0-param constructor and creates a “CricketTeam” class object using the parameterized constructor.

6. Add the jar file to the Build Path of the Project for the example of the constructor injection with XML configuration
Right Click on Project(Constructor_Injection_With_XML) ⇒ Build Path ⇒Java Build Path ⇒ libraries ⇒ Add External jars 

Commons-logging-<version>.jar
spring-beans-<version>.jar
spring-context-<version>.jar
spring-context-support-<version>.jar
spring-core-<version>.jar
spring-expression-<version>.jar

ClientApp.java:

package com.poc.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.poc.bean.CricketTeam;

public class ClientApp {

  public static void main(String[] args) {

    // load the spring Configuration file

    ClassPathXmlApplicationContext context =

      new ClassPathXmlApplicationContext("applicationContext.xml");

    //retrieve bean from spring container

    CricketTeam theTeam = context.getBean("team", CricketTeam.class);

    // call the method on bean

    System.out.println(theTeam.getInstruction());

    context.close();

  }

}

7. Run the App
Output:

Constructor: 0-param constructor call of CricketCoach
Constructor: parameterized constructor is called CricketTeam
Team Name: Mumbai Indians----6 hours of practice

Conclusion:
This example is explained What is Constructor Injection? How to Configure the Spring Bean classes in the XML file? Which tag to use for constructor injection in the XML file?

Leave a Comment