Spring – Dependency Injection

Spring – Dependency Injection

One of the main features of Inversion of Control (IoC) is Dependency Injection (DI). It is a process of supplying the dependencies from one object to others. The Spring-Core container module is responsible for injecting the dependencies. Dependency Injection is used to implement the Inversion of Control (IoC), or sometimes itself called Inversion of Control. The main motive of IoC is to keep all the Java classes independent from each other and provide automatic object creation. In Spring, Dependency Injection also ensures loose-coupling between the classes.

What is the need for Dependency Injection?

Let us understand this through an example. In an application, Class A needs the object of class B to call or operate a method such that, class A is dependent on class B. It might appear okay to depend on the other class, but in large scale applications, it will create a lot of problems. Hence, we need to avoid these types of dependencies.

Spring Inversion of Control (IoC) resolves such problems through Dependency Injection (DI). It makes the code more comfortable to use, learn, and test. Through DI, Loose-coupling can be possible between the classes by defining the interfaces.

Types of Dependency Injection

There are two types of dependency Injection present in Spring:

  1. Constructor Dependency Injection– In this DI type, the dependencies are injected with the help of a constructor. To set the dependency using Constructor, we need to add the dependency reference inside the <constructor-arg></constructor-arg> tag in the bean-Configuration file.

Following code shows how to add Constructor dependencies in the configuration file:

<bean>
<constructor-arg ref = "myfortune"></constructor-arg>
</bean> 

In the above code, myfortune is the reference to the constructor injection.

  • Setter Dependency Injection– In this DI type, the dependencies are injected with the help of a setter method. The Setter injection type is more accessible as compared to the Constructor injection. To set the dependency using setter, we need to add the dependency reference inside the <property></property>tag into bean-configuration file.

Following code shows how to add Setter dependencies in the configuration file:

<bean>
<property name = "fortuneservice" ref = "myfortune"></property>
</bean> 

Example of Constructor Dependency Injection

Let’s understand the Constructor Dependency Injection with the help of an example. In this example, the Fortune and Coach are the interfaces containing unimplemented methods. The GoodLuckFortune class implements the Fortune interface and its unimplemented methods. Similarly, the Cricket_Coach class implements the Coach interface and its unimplemented methods.

Following are the steps to create an example of Constructor Dependency Injection:

Fortune.java

public interface Fortune {
             public String fortuneService();
   } 

GoodLuckFortune.java

public class GoodLuckFortune implements Fortune {
             public String fortuneService() {
                         return "Goodluck for Today..!!";
             }
   } 

Coach.java

public interface Coach {
             public String workout();
             public String getDailyFortune();
  }  

Cricket_Coach.java

public class Cricket_Coach implements Coach {
             private Fortune fortuneservice;
                        // setting a Constructor
             public Cricket_Coach(Fortune fortuneservice) {
                         super();
                         this.fortuneservice = fortuneservice;
             } 
             public String workout() {
         return "daily 1 hour of running ";
          }
       public String getDailyFortune() {
         return fortuneservice.fortuneService();
             }
   } 

In the above Cricket_Coach class, we have created an arg-constructor for performing dependency injection.

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"
         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.0.xsd">
 <!--Define the dependency -->
 <bean id = "myfortune" class = "com.app.SpringDI.GoodLuckFortune"></bean>
 <bean id = "mycoach" class ="com.app.SpringDI.Cricket_Coach">
 <!-- setup the Constructor Injection -->
 <constructor-arg ref = "myfortune"> 
 </constructor-arg> 
 </bean>
 </beans> 

The above bean-configuration file (applicationContext), contains the bean information inside the <beans></beans> tag. The <beans>tag is used to define multiple beans. Inside the beans tag, <bean></bean> tag is defined for defining different beans. The <bean>tag is used to define a single bean class.

It also contains the constructor reference for dependency injection inside the <constructor-arg></constructor-arg>tag.

App.java

import org.springframework.context.ApplicationContext;
 import org.springframework.context.support.ClassPathXmlApplicationContext;
 public class App 
 {
     public static void main( String[] args )
     {
                     ClassPathXmlApplicationContext appcontext = new ClassPathXmlApplicationContext("applicationContext.xml"); 
             System.out.println("loading");
             Coach co = appcontext.getBean("mycoach", Coach.class);
             System.out.println(co.getDailyFortune());
             System.out.println(co.workout());
     }
 } 

The above App class contains the main() method.

OUTPUT

App class contains the main() method

Now, we are going to create an example of Setter Dependency Injection.

Example of Setter Dependency Injection

We have discussed above the example of Constructor dependency injection. Now, we will create the SDI example. It is similar to the above example. Fortune and Coach are the interfaces with the unimplemented methods. The GoodLuckFortune and Cricket_Coach are the Bean classes which implement the Fortune and Coach interface, respectively.

Following are the steps to create an example of Setter dependency injection:

Fortune.java

public interface Fortune {
             public String fortuneService();
 } 

GoodLuckFortune.java

public class GoodLuckFortune implements Fortune{
             public String fortuneService() {
                         return "Goodluck for Today..!!";  
             }
 } 

Coach.java

public interface Coach {
             public String workout();
             public String getDailyFortune();
 } 

Cricket_Coach.java

public class Cricket_Coach implements Coach {
             private Fortune fortuneservice;
              //setter method for dependency injection
             public void setFortuneservice(Fortune fortuneservice) {
                         this.fortuneservice = fortuneservice;
                         System.out.println("setter method for dependency injection");
             } 
             public String workout() {
               return "daily 1 hour of running ";
             }
             public String getDailyFortune() {
             return fortuneservice.fortuneService();
             }
 } 

In the above Cricket_Coach class, we have used the setter method for performing the dependency injection.

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"
         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.0.xsd">
 <!--Define the dependency  -->
 <bean id = "myfortune" class= "com.app.SpringDI.GoodLuckFortune"></bean>
 <bean id = "mycoach" class ="com.app.SpringDI.Cricket_Coach">
 <!-- setting up the Setter Injection -->
 <property name = "fortuneservice" ref = "myfortune"></property>
 </bean> 
 </beans> 

In the above xml file, we have defined the dependency reference inside the <property></property> tag.

App.java

import org.springframework.context.ApplicationContext;
 import org.springframework.context.support.AbstractApplicationContext;
 import org.springframework.context.support.ClassPathXmlApplicationContext;
 public class App 
 {
     public static void main( String[] args )
     { 
             ApplicationContext appcontext = new ClassPathXmlApplicationContext("applicationContext.xml");
             Coach co = appcontext.getBean("mycoach", Coach.class);
             System.out.println(co.getDailyFortune());
             System.out.println(co.workout());
     }
 } 

OUTPUT

we have defined the dependency reference inside the property