Saturday, 6 April 2013

Inversion Of Control and Dependency Injection in Spring

IOC

    IOC stands for Inversion of Control. Before going to know about what is inversion of control we need to know why inversion of control was introduced.

Tight coupling : The problem

    Inversion of control was introduced to overcome the problem of tight coupling between java objects. Let us have a look at the concept of tight coupling with an example.

public class Customer {


private Address address; 

public Customer() {
  address = new Address(); // Problem: object creation
}

}

The major problem in the above example is object of address class is created in Customer class constructor. In other words Customer class is controlling object creation process of Address class. If there are any changes in Address class then we have to change the code in Customer class.
For example say there is only a parameterized constructor in class Address then we should change the code of Customer class constructor. Hence we can say that both Customer and Address classes are tightly coupled.

Inversion of Control : The Solution
    Definitely the solution resides in shifting the object creation control form Customer class to someone else. If we are able to invert this control to a third party we have found the solution. So the name the solution is Inversion Of Control (IOC)


Above Customer class can be modified to support Inversion of control as shown below




In the above example we have given the object creation control to a IOC Framework. The functionality of IOC Framework are shown below
  • Creates the address object
  • Creates the customer object
  • Injects address object into the customer object 


Dependency Injection:


Above diagram shows how IOC and DI are organised. Concluding the above discussion we can say that IOC is a principle and Dependency Injection is a way of implementing IOC principle

From the above diagram we can find there are three types of Dependency Injections

  • Setter injection
  • Constructor injection
  • Interface injection
Spring supports only Setter and Constructor type of injections

I will discuss in details regarding setter and constructor injection in my next post.

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Thank it is very important and easily understanding

    ReplyDelete