A Naive Example of Dependency Injection

–> It’s a way in which you decouple the conventional dependency relationships between objects.

Say we have two objects that are related to each other, one is dependent on the other. The idea is decouple this dependency. So that they’re not tied to each other.

Two Different Classes
Circle c = new Circle();
c.draw();

Triangle t = new Triangle();
t.draw();

We can use polymorphism:

Realization: Circle and Triangle implements Shape interface.
Shape s1 = new Circle();
s1.draw();

Shape s2 = new Triangle();
s2.draw();

Still tying the code to a triangle or a circle. It still hard coded to use either a triangle or a circle.

// Applicaiton Class

public void myDrawMethod(Shape shape) {
shape.draw();
}

// Somewhere else in the class

Shape shape = new Triangle();
myDrawMethod(shape);

We still tied to this new Triangle, still not free from it. Somewhere else in the class we need to instantiation.

Class Member Variable:

public class Drawing {

 private Shape shape;

   public void setShape(Shape shape) {
    this.shape = shape;
   }

   public void drawShape() {
    this.shape.draw();
   }

}

Now totally removed the dependency from Triangle or Circle. If you want to draw a triangle or circle we don’t have to modify the drawing class. This is going to remain the same, all we need to do is pass a triangle or circle to the setter.

// Different Class

Triangle t = new Triangle();
Drawing d = new Drawing();
d.setShape(t);
d.drawShape();

Advantage is here is that in Drawing class instead of having an instance of a specific shape as a triangle or a circle, it has an instance of the parent shape object.

We are separating the whole dependency out of a class, the Drawing class doesn’t really know what its dependent on, it really doesn’t know what it’s drawing and the advantage of this is that if what it has to draw changes we don’t have to modify the Drawing class.

Dependency to the triangle is actually injected to the Drawing class by something else, it’s injected by a completely different class. This is the principle of dependency injection.

We just tell Spring saying here have this object (Triangle or Circle), now inject this dependency to this object. We just call the drawShape() and then configure Spring to inject the right dependencies to the right objects and Spring takes care of that.

About Aliyar Güneş

I’am Aliyar Güneş, a learner and software developer from Istanbul, Turkey. I write C# and Java.
This entry was posted in Spring Framework, Works and tagged , . Bookmark the permalink.

Leave a Reply