Saturday 2 February 2019

What is IOC and Dependency Injection? (Need of Spring with real life example)

The concept of IOC (Inversion of control) says just to use object and dependencies should be delegated (give responsibility) to a runtime environment that is IOC container in Spring.

IOC (Inversion of control) deals with 3 things:

        1. Object Creation,
        2. Dependency Satisfaction and
        3. Lifecyle Management.

For instance, Let an application wants to use an object A which needs another object B. So, the "Conventional Approach" is here's the diagram that shows an application wants to use A that is dependent on B.

In "Conventional Approach" there are 4 steps and all are from application side:

        1.0 - Application firstly creates A object,
        1.1 - Application creates B object as well,
        1.2 - Reference of B is given to A
        1.3 - A object is used by application (i.e. some method is invoked on it).

Now look at "IOC Based Approach", the scenario is same an application wants to use A that needs B.

In "IOC Based Approach" there are 6 steps but only 2 from application side that is requesting for an object and using it:

        1.0 - A object is requested by application,
        1.1 - A object is created by the container,
        1.2 - B object is created by the container to satisfy the dependency of A,
        1.3 - Reference of B object is given to A object,
        1.4 - Reference of A object is returned to the application,
        1.5 - A object is used by application (i.e. some method is invoked on it).


The IOC based approach is "Dependency Injection" that simply means IOC container is injecting/satisfying the dependencies and the main advantage of dependency injection is it solves maintenance problem.

And to clear your doubt, IOC is a concept and that follows this concept in Spring is IOC container. Name can be different in other languages like in angular we call it "Providers" but the concept is same.

In our real life IOC is everywhere, Let's take some real life examples. When you tell your mom that you're feeling hungry and you need food then your mom will put whatever available in the kitchen like rice,veggies etc. in a plate and serve to you that's what IOC does for you. You simply ask for an object, IOC container will create and satisfy all the dependencies and give that object to you.

Now let's take another example, to drive a bike you're not making roads. Roads are already made available to you, all you need is just drive your bike.

And this spring boot series will be focusing on all the concepts of spring in-depth using spring boot because plain spring is old school stuff.

0 comments:

Post a Comment