Pages

Wednesday, 6 September 2017

Spring Dependency Injection with examples


Introduction :
  • Dependency Injection (DI) is a design pattern that removes the dependency from the programming code so that it can be easy to manage and test the application. Dependency Injection makes our programming code loosely coupled.
  • Dependency Injection was originally called Inversion of Control (IoC) because the normal control sequence would be the object finds the objects it depends on by itself and then calls them. Here, this is reversed: The dependencies are handed to the object when it's created. This also illustrates the Hollywood Principle at work: Don't call around for your dependencies, we'll give them to you when we need you.
  • To understand the Dependency Injection better, Let's understand the Dependency Lookup (DL) first:


Dependency Lookup :
  • The Dependency Lookup is an approach where we get the resource after demand. There can be various ways to get the resource for example:          
           Address add = new Address();
  • In such way, we get the resource(instance of Address class) directly by new keyword. Another way is factory method:
          Address add = Address.getAddress();
  • This way, we get the resource (instance of Address class) by calling the static factory method getAddress().
  • Alternatively, we can get the resource by JNDI (Java Naming Directory Interface) as:
ApplicationContext ctx;
ctx = (ApplicationContext) schedulerContext.get("applicationContext");
Address address = (Address) ctx.getBean("address");

Problem of Dependency Lookup :
  • There are mainly two problems of dependency lookup.

  1. Tight coupling The dependency lookup approach makes the code tightly coupled. If resource is changed, we need to perform a lot of modification in the code.
  2. Not easy for testing This approach creates a lot of problems while testing the application especially in black box testing.

Spring Dependency Injection :
  • Let’s say we want to send email message and twitter message to the users. For dependency injection, we need to have a base class for the services. So I have MessageService interface with single method declaration for sending message.

  • Two ways to perform Dependency Injection in Spring framework :
  1. By Constructor
  2. By Setter method



Examples


1. Dependency Injection By Constructor:

Student.java
  • It is a simple class containing two fields id and name. There are four constructors and one method in this class.
package com.springDependencyInjection;

public class Student {
private int id;
private String name;
public Student(int id){
this.id=id;
}
public Student(String name){
this.name=name;
}
public Student(int id,String name){
this.id=id;
this.name=name;
}
public void display(){
System.out.println("Student Id :"+id);
System.out.println("Student Name :"+name);
}
}

ApplicationContext.xml
  • We are providing the information into the bean by this file.The constructor-arg element invokes the constructor. In our case parameterize constructor will invoke for integer and string types one by one as argument passed in int and string.
<?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">  

<bean id="studInfo" class="com.springDependencyInjection.Student">  
      <constructor-arg value="46" type="int"></constructor-arg>
      <constructor-arg value="Harshad"></constructor-arg>
</bean>
</beans>


Test.java
  • This class gets the bean from the applicationContext.xml file and calls the show method.
package com.springDependencyInjection;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;  

public class Test {
public static void main(String[] args) {  
              ApplicationContext cnt;
              cnt = new ClassPathXmlApplicationContext("applicationContext.xml");
  Student stud=(Student)cnt.getBean("studInfo");  
  stud.display();            
 }  
}
Output
Student Id : 46
Student Name : Harshad

2. Dependency Injection By Setter Method:

  • We can inject the dependency by setter method also. The <property> subelement of<bean> is used for setter injection. Here we are going to inject.

  1. Primitive and String-based values
  2. Dependent object (contained object)
  3. Collection values etc.

  • Let's see the simple example to inject primitive and string-based values by setter method. We have created three files here:
Student.java
  • It is a simple class containing three fields id, name and city with its setters and getters and a method to display these informations.
package com.springDependencyInjection;

public class Student {
private int id;
private String name;
private String city;
public int getId() {  
  return id;  
}  
public void setId(int id) {  
  this.id = id;  
}  
public String getName() {  
  return name;  
}  
public void setName(String name) {  
  this.name = name;  
}  
public String getCity() {  
  return city;  
}  
public void setCity(String city) {  
  this.city = city;  
}  
public void display(){
System.out.println("Student Id :"+id);
System.out.println("Student Name :"+name);
System.out.println("Student City :"+city);
}
}

ApplicationContext.xml
  • We are providing the information into the bean by this file. The property element invokes the setter method. The value subelement of property will assign the specified value.
<?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">  
<bean id="studInfo" class="com.springDependencyInjection.Student">  
<property name="id">  
<value>46</value>  
</property>  
<property name="name">  
<value>Harshad</value>  
</property>  
<property name="city">  
<value>Jamnagar</value>  
</property>
</bean>
</beans>  


Test.java
  • This class gets the bean from the applicationContext.xml file and calls the show method.
package com.springDependencyInjection;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;  

public class Test {
public static void main(String[] args) {  
               ApplicationContext cnt;
               cnt = new ClassPathXmlApplicationContext("applicationContext.xml");
   Student stud=(Student)cnt.getBean("studInfo");  
   stud.display();            
  }  
}
Output
Student Id :46
Student Name :Harshad
Student City :Jamnagar

No comments:

Post a Comment