What is Dependency Injection in Spring

In the previous article, we have seen What is IOC i.e Inversion of Control in Spring Framework? You can check it here What is IOC Container in Spring which is the most important concept of the framework. Now, In this article, we will cover what is Dependency Injection?

As a Developer, everyone wants to build a reusable code and avoid changes in a class more often. Dependency Injection is a concept that plays a vital role in decoupling the creation and usage of the Object.

From the Dependency word itself, we can understand “to depend”. As we know, we create too many classes in the project where one functionality of Class 1 depends on Class 2, Class 2 depends on Class ‘n’. So, here we can say Class A has a dependency on class B. Spring Framework will take the responsibility of  Injecting this dependency. 

What is Dependency Injection?

In order to use the functionality of one class into other, In Java Programming we create the Object and use it in the class. So, to avoid using the creation of an object in other classes and transferring the task of creating an object to Container and directly using the dependency is called Dependency Injection.

Let us take a Real-time example of Dependency Injection.

Consider a Person “Nicolas”. To Survive in this world he needs three things: Food, Clothing & Shelter. So, we can call it a dependency. Let’s map this example in our programming way. We can consider a Person as a Class and Food, Clothing & Shelter as another class where a person object depends on these three classes.

So, to use this dependency Person Class needs to create an object. But In Spring Framework, The responsibility of creating the object will go to the IOC Container. If you don’t know what is IOC COntainer is please refer to this article What is IOC Container in Spring. Spring will Inject this Dependency inside the class using:

  • Setter Method
  • Constructor

Example of Dependency Injection using Setter Method

Create a Spring Project Go to File> New > Other > Search maven > Select Maven Project > Next > Search Filter org.apche.maven.archetypes/webapp > Next > Enter Group Id & Archetype id > Finish.

  • Create a Class Person having a name attribute/property and a setter method.
package com.codedec.di;

public class Person {

   private String name;    // This is the dependency of Person class
  public void setName(String name) {
    this.name = name;
  }
  public void	show() {
    	 System.out.println("Name of person is :: " +name);
     }
  
  
}
  • Create an App.java class to set values. Now, In order to set the name, we will call the setter method of Person class and will pass the hardcoded value.
package com.codedec.di;

public class App {

  public static void main(String[] args) {
    Person person = new Person();
    person.setName("Nicolas");
    person.show();
  }
}
  • Now, the value will be set and you will get the following Output.
Name of person is :: Nicolas
  • Here, we have to create an object of the Person class. But, we are using Spring Framework, so we will give the responsibility of creating the object to Spring.
  • we will inject the dependency using the setter method.
  • <bean> element sub-property <property> is used for setter injection. 
  • The <property> element here will invoke the setter method.
  • Make sure the ‘name’ in the property name field is the same as that of the Person class attribute ‘name’.
<?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">
  <bean id="person" class="com.codedec.di.Person">
    <property name="name" value="Nicolas"></property>
  </bean>

</beans>
  • In App.java create the Object of Application Context and call the show() method.
package com.codedec.di;

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

public class App {

  public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
     Person p1 = context.getBean("person",Person.class);
     p1.show();
  }
}

Thus, This is how we Inject the dependency using the Setter method property.

Example of Dependency Injection using Constructor

  • Create a class Person with a name & city attribute.
package com.codedec.di;

public class Person {

  private String name, city; // This is the dependency of Person class

  public Person(String name, String city) {
    this.name = name;
    this.city = city;
  }

  public void show() {
    System.out.println("Name of person is :: " + name + "\n City of person is :: " + city);
  }

}
  • Create beans.xml file with <constructor-arg> property 
  • The <constructor-arg> element invokes the constructor of the Person class.
<?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">
  <bean id="person" class="com.codedec.di.Person">
    <constructor-arg name="name" value="Nicolas" ></constructor-arg>
    <constructor-arg name="city" value="Amsterdam" ></constructor-arg>
  </bean>

</beans>
  • In App.java create the Object of Application Context and call the show() method.
package com.codedec.di;

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

public class App {

  public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
     Person p1 = context.getBean("person",Person.class);
     p1.show();
  }
}

Output: 

Name of person is :: Nicolas
 City of person is :: Amsterdam

Thus, This is how we Inject the dependency using the constructor property.

Thus, In this article, we Inject the dependency using setter and Constructor.