Friday, 20 December 2013

Dependency Injection

Dependency Injection takes the level of decoupling that began with the Dependency Inversion Principle one step further.

Dependency injection has the concept of an assembler or what in Java is commonly referred to as a Factory -- that instantiates the objects required by an application and “injects” them into their dependent objects.



In the case of a dependency injection-informed framework such as Spring, components are coded to interfaces, just as in the DIP example above. But now the IoC container manages the instantiation, management, and class casting of the implemented objects so that the application doesn't have to.
This removes any true dependencies on low-level implemented classes.

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

The Dependency Injection is a design pattern that removes the dependency of the programs. In such case we provide the information from the external source such as XML file. It makes our code loosely coupled and easier for testing. In such case we write the code as:

    class Employee{ 
    Address address; 
     
    Employee(Address address){ 
    this.address=address; 
    } 
    public void setAddress(Address address){ 
    this.address=address; 
    } 
     
    }

In such case, instance of Address class is provided by external souce such as XML file either by constructor or setter method.
Two ways to perform Dependency Injection in Spring framework

Spring framework provides two ways to inject dependency

    By Constructor
    By Setter method

No comments:

Post a Comment