Constructor Dependency Injection

Types of Dependency Injection based on how we inject the dependent beans

1. Constructor DI

2. Setter DI


Constructor Dependency Injection ?


Constructor DI is the method of injecting dependent beans through constructor

It means, we pass all the dependent objects as parameters to the constructor and wire them accordingly in the spring configuration file.

We can also inject primitive values through constructor.

Let us see the same with below example

We have Person and Country classes where each person will have an associated country.

So Person is dependent on Country.

Create Person.java

  1. package com.kb.di;
  2.  
  3. public class Person {
  4.     private int id;
  5.     private String name;
  6.     private int age;
  7.     private Country country;
  8.     public int getId() {
  9.         return id;
  10.     }
  11.     public Person(int id, String name, int age, Country country) {
  12.         super();
  13.         this.id = id;
  14.         this.name = name;
  15.         this.age = age;
  16.         this.country = country;
  17.     }
  18.     @Override
  19.     public String toString() {
  20.         return "Person details -> id "+id+" name "+name+" age "+age;
  21.     }
  22.    
  23.     public void showPerson(){
  24.     System.out.println(toString());
  25.     System.out.println(country.toString());
  26.     }
  27. }
package com.kb.di;

public class Person {
	private int id;
	private String name;
	private int age;
	private Country country;
	public int getId() {
		return id;
	}
	public Person(int id, String name, int age, Country country) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
		this.country = country;
	}
	@Override
	public String toString() {
		return "Person details -> id "+id+" name "+name+" age "+age;
	}
	
	public void showPerson(){
	System.out.println(toString());
	System.out.println(country.toString());
	}
}


It contains 3 primitive attributes and 1 dependent object reference to Country.

Person class has a constructor which takes all the 4 parameters and these parameters are injected in the spring configuration file

There is also a toString() method which returns the values of Person

Create Country.java

  1. package com.kb.di;
  2.  
  3. public class Country {
  4.     private int id;
  5.     private String name;
  6.     public Country(int id, String name) {
  7.         super();
  8.         this.id = id;
  9.         this.name = name;
  10.     }
  11.    
  12.     @Override
  13.     public String toString() {
  14.         return "Country details -> id "+id+" name "+name;
  15.     }
  16.    
  17. }
package com.kb.di;

public class Country {
	private int id;
	private String name;
	public Country(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
	
	@Override
	public String toString() {
		return "Country details -> id "+id+" name "+name;
	}
	
}

It contains 2 primitive attributes

Country class has a constructor which takes all the 2 parameters and these parameters are injected in the spring configuration file

There is also a toString() method which returns the values of Country

Create Spring configuration file(xml file)

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.     xmlns:p="http://www.springframework.org/schema/p"
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans
  6.        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
  7.  
  8.   <bean id="country" class="com.kb.di.Country">  
  9.     <constructor-arg value="1" type="int"></constructor-arg>  
  10.     <constructor-arg value="India"></constructor-arg>  
  11.   </bean>  
  12.    
  13.  <bean id="person" class="com.kb.di.Person">  
  14.     <constructor-arg value="1" type="int"></constructor-arg>  
  15.     <constructor-arg value="Raj"></constructor-arg>
  16.     <constructor-arg value="22" type="int"></constructor-arg>
  17.     <constructor-arg>  
  18.     <ref bean="country"/>  
  19.     </constructor-arg>  
  20.  </bean>  
  21.  
  22.   </beans>
<?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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
  
  <bean id="country" class="com.kb.di.Country">  
	<constructor-arg value="1" type="int"></constructor-arg>  
	<constructor-arg value="India"></constructor-arg>  
  </bean>  
    
 <bean id="person" class="com.kb.di.Person">  
	<constructor-arg value="1" type="int"></constructor-arg>  
	<constructor-arg value="Raj"></constructor-arg> 
	<constructor-arg value="22" type="int"></constructor-arg> 
	<constructor-arg>  
	<ref bean="country"/>  
	</constructor-arg>  
 </bean>  

  </beans>


< constructor-arg > tag is used to inject the values through constructor

value attribute inside < constructor-arg > tag is used to specify the value.

type attribute inside < constructor-arg > tag is used to specify the data type of value we are passing, it should match with the type defined in java class
default type attribute in spring is ‘String’,so we have not specified type for all such string values.

ref is used to specify the reference to another bean with its id.
In this case, it is referring to country.

Pom.xml file

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3.   <modelVersion>4.0.0</modelVersion>
  4.  
  5.   <groupId>Spring</groupId>
  6.   <artifactId>SpringCore</artifactId>
  7.   <version>0.0.1-SNAPSHOT</version>
  8.   <packaging>jar</packaging>
  9.  
  10.   <name>SpringCore</name>
  11.   <url>http://maven.apache.org</url>
  12.  
  13.   <properties>
  14.     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  15.   </properties>
  16.  
  17.   <dependencies>
  18.   <dependency>
  19.     <groupId>org.springframework</groupId>
  20.     <artifactId>spring-core</artifactId>
  21.     <version>4.2.4.RELEASE</version>
  22. </dependency>
  23.   <dependency>
  24.     <groupId>org.springframework</groupId>
  25.     <artifactId>spring-context</artifactId>
  26.     <version>4.2.4.RELEASE</version>
  27. </dependency>
  28.  
  29.     <dependency>
  30.       <groupId>junit</groupId>
  31.       <artifactId>junit</artifactId>
  32.       <version>3.8.1</version>
  33.       <scope>test</scope>
  34.     </dependency>
  35.   </dependencies>
  36. </project>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>Spring</groupId>
  <artifactId>SpringCore</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>SpringCore</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
  <dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-core</artifactId>
	<version>4.2.4.RELEASE</version>
</dependency>
  <dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context</artifactId>
	<version>4.2.4.RELEASE</version>
</dependency>
  
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>


Spring core related dependencies are specified in this pom.xml

Create Main class(ConstructorDI)

  1. package com.kb.di;
  2.  
  3. import org.springframework.beans.factory.BeanFactory;
  4. import org.springframework.beans.factory.xml.XmlBeanFactory;
  5. import org.springframework.core.io.ClassPathResource;
  6. import org.springframework.core.io.Resource;
  7.  
  8. public class ConstructorDI {
  9.    
  10.     public static void main(String[] args) {
  11.         Resource resource=new ClassPathResource("beans.xml");  
  12.         BeanFactory beanFactory=new XmlBeanFactory(resource);  
  13.         Person person = (Person)beanFactory.getBean("person");  
  14.         person.showPerson();
  15.     }
  16.  
  17. }
package com.kb.di;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class ConstructorDI {
	
	public static void main(String[] args) {
	    Resource resource=new ClassPathResource("beans.xml");  
        BeanFactory beanFactory=new XmlBeanFactory(resource);  
        Person person = (Person)beanFactory.getBean("person");  
        person.showPerson();
	}

}


Now right click on ConstructorDI class and run as java application

Output


Download this project SpringDI.zip

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on