What is IoC? What is Dependency Injection?

What is Inversion of Control (IoC)?

IoC is a framework used to create and inject dependencies automatically and manages its lifecycle.

To put this in a more understandable concept, let’s say a developer is trying to create a new object, you would need “new ThisNewObject” inside of the code, which creates a rigid bond between classes. What IoC does is that it creates this new object for the developer so that the previously mentioned step is avoided which results to your code being less rigid.

What IoC does to achieve the this is by scanning the annotations within your code to find objects. The annotation is searched by the Component Scanner, which looks for classes with annotations such as @Component, @Services, @Controller or @Repository. It finds the objects within the class and turns them into a Singleton Bean. After that process, the Beans get put into the IoC container, which then goes through the Bean Lifecycle. And throughout the lifecycle, the beans get initialized, used for its purpose and removed all through the management of IoC.

What is Dependency Injection (DI)?

DI is a way of making hard coded dependencies, loosely coupled. This could be done in a couple different methods: by using parameter in a constructor or through a setter method.

Hard-coded dependency:

public class ThisClass {

private ThisDependency thisDependency = new ThisDependency();

}

DI via parameter in a constructor:

public class ThisClass {

private ThisDependency thisDependency;

public ThisClass (ThisDependency thisDependency) {

this. thisDependency = thisDependency;

}

}

DI via setter method:

public class ThisClass {

private Object thisDependency;

public Object getThisDependency () {

return thisDependency;

}

Public void setThisDependency (Object thisDependency) {

this.thisDependency = thisDependency;

}

}