Dependency Injection

It is sometime called dependency inversion.

It is a way in which you decouple the coventional dependancy relationship betweent objects.Say you have two objects that are related to each other one is dependent on other. The concept to decouple this dependancy so that they are not tied to each other.

Spring Dependancy Injection

Above in Application class we have hard coded triangle object and circle object.

Now if i want to draw some other shape instead of circle say rectangle so i have to change my code in Application class.So overall it means my Application class has hard coded depandency.

Do it using Polymorphism

This is polymorphism in action.

Spring Dependancy Injection

If shape has triangle it calls triangle's draw method. If shape has circle object it calls circle's draw method.

Here instead of calling method of the object itself we have a handle to this parent object (Shape) . Parent object could be abstract class or interface

But still its hard coded as we are creating instance of Circle and Triangle.

Polymorphism using a method

Here myDrawMethod does not worry about what shape it is ,it knows that what ever objet is being passed as shape and it will call a draw method depanding on object passed as circle object or triangle method

So we removed dependency of circle or triangle from myDrawMethod().

But still somewhere shape object is created and this myDrawMethod() is called so there has to be some another piece of code in this class which has initialization Shape=new Triangle() . Then we need to call myDrawMethod(shape) So we still tied to this new Triangle().

myDrawMethod Method is insulated.we have taken depandency from this method.

Spring Dependancy Injection

Decouple Dependency From Application class

Spring Dependancy Injection