Inversion of Control

Inversion of Control (IoC) is a programming principle that is at the core of the Spring Framework, and it is a design pattern that decouples the creation of objects and their dependencies. It means that the control of the objects and their dependencies is “inverted” or reversed, instead of the developer creating and managing the objects and their dependencies, the container (i.e., Spring Framework) is responsible for creating and managing the objects and their dependencies.

Ioc Implementations:

  • Service Locator Pattern
  • Dependency Injection
  • Events
  • Delegates

Dependency Injection:

Dependency Injection (DI) is a design pattern that is used to implement IoC. It is a way to provide the objects with their required dependencies. The developer defines the dependencies in the configuration files and the container creates and manages the objects and their dependencies. It allows for a more loosely coupled and maintainable codebase.

 Dependency Injections is a sub-type of IoC and is implemented by constructor injection, setter injection or Interface injection.

Spring supports the following two types :

  • Setter Injection
    • Setter-based DI is by calling setter methods on the user’s beans after invoking a no-argument constructor or no-argument static factory method to instantiate their bean.
  • Constructor Injection
    • Constructor-based DI is by invoking a constructor with a number of arguments, each representing a collaborator.Using this we can validate that the injected beans are not null and fail fast(fail on compile time and not on run-time), so while starting application itself we get NullPointerException: bean does not exist.

Constructor injection is Best practice to inject dependencies.

Summary of IoC vs DI:

  • IoC is a design principle that describes how objects should be created and their dependencies managed
  • DI is a way of implementing that principle by having the container manage the dependencies.
  • Without IoC, there would be no need for DI.
  • It is possible to use DI without using IoC.