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


Related Topics

Spring - Bean Scopes with Annotations

Spring - Bean Scopes with Annotations We have previously discussed the Spring bean scopes using an XML-based configuration. In the XML-based configuration, we have defined the beans and its scope inside the bean-config...

3 minutes read.

Spring AOP – @After Advice

Spring AOP – @After Advice We have previously discussed the concepts of Spring AOP. One of the AOP concepts is Advice, which is further divided into various types. After (finally) is a type of advice...

3 minutes read.

Spring – Configuration using @Configuration

Spring – Configuration using @Configuration We have previously discussed the Spring configuration using an XML configuration file. In that case, we have defined all the bean information in the bean-configuration file (applicationContext.xml). ...

3 minutes read.

Spring MVC Form – Drop-Down List

We have already discussed the Spring MVC form tags available in the form tag library. Form tags are used to develop web applications easily. In this tutorial, we are going to discuss the...

13 minutes read.

Spring Autowiring – Setter Injection

Spring Autowiring – Setter Injection We have previously discussed an example of Setter Dependency Injection (SDI) using an XML file. In the previous case, we have defined the property name for the dependency...

2 minutes read.

Spring – Bean Lifecycle

Spring – Bean Lifecycle Spring bean is responsible for managing the lifecycle of beans created by the Spring container.  The lifecycle of the bean is easy to understand. When a bean is created, it requires...

4 minutes read.

Spring AOP – @AfterReturning Advice

Spring AOP – @AfterReturning Advice We have discussed earlier the types of advices available in Spring AOP. One of them is After Returning advice. It is an advice that executes after the normal execution...

3 minutes read.

Spring AOP – @Before Advice Type

Spring AOP – @Before Advice Type As we have discussed, AOP (Aspect-Oriented Programming) is one of the powerful features of the Spring framework. It complements the Object-Oriented Programming (OOPs). AOP provides some concepts and terminology,...

2 minutes read.

Spring - Injecting values from Property Files

Spring - Injecting values from Property Files In this section, we will discuss how to inject values from a property file using the Java-based configuration. Here, we will use two annotations @Value and @PropertySource...

3 minutes read.

Spring AOP - @AfterThrowing Advice

Spring AOP - @AfterThrowing Advice As we have discussed in our previous tutorial, Advice is one of the essential concepts of the Spring AOP. The after throwing advice is one of the types of...

3 minutes read.

Spring MVC Example – Reading HTML Form Data

We have discussed earlier a simple example of Spring MVC in which we have created multiple view pages. Here, we are going to create another Spring MVC example in which we are...

7 minutes read.

Spring Autowiring –Field Injection

Spring Autowiring –Field Injection The Field Injection is used to inject the fields, variables, or properties of the beans. It is not available in autowiring using XML- based configuration. It is a...

2 minutes read.

Spring Model Interface

Model Interface Model is an interface that defines a holder for model attributes. It is also used to transfer data between various parts of the Spring MVC application. The Model interface is available...

8 minutes read.

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...

8 minutes read.

Spring – Beans using @Bean

Spring – Beans using @Bean We have previously discussed an example of Spring configuration using an XML-based configuration. In the previous example, we have defined beans inside the bean-configuration file (applicationContext.xml). To make the...

3 minutes read.

Spring - Bean lifecycle using annotations

Spring - Bean lifecycle using annotations We have already discussed the bean lifecycle using an XML-based configuration. In the previous case, we have declared the init-method and destroy-method attributes in the bean-configuration file. Here, we...

2 minutes read.

Spring MVC Form Checkbox

Spring MVC provides several form tags used to develop web applications (Usually JSP pages). One of them is a checkbox tag. The checkbox tag offers us to choose multiple options at the same...

12 minutes read.

Spring - Inversion of Control (IoC)

Spring - Inversion of Control (IoC) The Inversion of Control (IoC) is a process where the objects define their dependencies, that is, the dependencies of other objects with they are working. It is done...

4 minutes read.

Spring MVC Example

Spring MVC Example We have previously discussed the Spring Web MVC framework. In this tutorial, we are going to create a simple example of Spring Web MVC. Following are the steps used to create an example...

2 minutes read.

Spring MVC Regular Expression Validation

Example of Regular Expression Validation Here, we are going to create an example of regular expression validation. Following are the steps to create an example of a regular expression: Create a request page In this step, we are going...

13 minutes read.