Dependency Injection in Spring

Dependency Injection (DI) is a configuration design pattern that expels the reliance from the programming code so it can be anything but difficult to oversee and test the application. Dependency Injection makes our programming code loosely coupled. To comprehend the DI better, Let's comprehend the Dependency Lookup (DL) first:

Issues of Dependency Lookup

There are for the most part two issues of reliance lookup.

  • Tight coupling The dependency lookup methodology makes the code firmly coupled. On the off chance that asset is transformed, we have to perform a great deal of adjustment in the code.
  • Not easy for testing This approach creates a lot of problems while testing the application especially in black box testing.

Dependency Injection

In such case, example of Address class is given by outer source, for example, XML record either by constructor or setter system.The Dependency Injection is a design pattern that removes the dependency of the programs.

class Employee{
Address address;

Employee(Address address){
public void setAddress(Address address){


In such case, instance of Address class is provided by external souce such as XML file either by constructor or setter method.

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:

A obj = new AImpl();

In such way, we get the resource(instance of A class) directly by new keyword. Another way is factory method:

A obj = A.getA();

This way, we get the resource (instance of A class) by calling the static factory method getA().

Alternatively, we can get the resource by JNDI (Java Naming Directory Interface) as:

Context ctx = new InitialContext();
Context environmentCtx = (Context) ctx.lookup("java:comp/env");
A obj = (A)environmentCtx.lookup("A");

There can be various ways to get the resource to obtain the resource. Let's see the problem in this approach.

Two ways to perform Dependency Injection in Spring framework

Spring framework provides two ways to inject dependency

  • By Constructor
  • By Setter method