• Shashank shekhar Dubey

[Summary] Dependency Injection

Updated: Dec 4, 2021

Consider the two classes given below:

class RAM{
  int size;
  String type;
}

class Laptop{
    String brand;
    RAM ram;
}

Class Laptop has a property that is an object of class RAM. Object ram has to be created using new inside Laptop so as to create and use the objects of Laptop. This usage of new results in a tightly coupled code. This scenario is even understandable since there is only one way of creating the objects of RAM:

ram = new RAM();

Now consider the following code:

interface I_RAM{
  
}

class SRAM implements I_RAM{

}

class DRAM implements I_RAM{

}

class Laptop{
    String brand;
    I_RAM ram;
}

In this design, we have an interface I_RAM that is used to create a reference for the type of RAM chosen by the user. We can use this design if there are multiple kinds of RAM and we want to give freedom to our users to choose any. It can also be used to restrict the user to choose the RAM of only the available kinds (Since there is no class for VRAM, the user can not choose it). But it raises the complication for the developer. Now there are two ways to initialize the class:

ram = new SRAM();
or
ram = new DRAM();

One way to work with this arrangement is to ask every user what kind of RAM they want to use and then edit the code accordingly. This will require compiling code separately for each user. I think how bad is this arrangement, need no explanation further.

We implement this requirement using the dependency injection mechanism. In this, the objects created using ey can specify their choice and our code simply makes the object of that kind without having to change or recompile the code. Now that sounds cheesy.

We implement this requirement using the dependency injection mechanism. In this, the objects created using new are the dependencies and we inject those objects into the code using an external configuration file.


Spring framework provides several ways of implementing dependency injection in JAVA.

10 views0 comments