Sobes.tech
Senior

Tell me about the principle of Dependency Injection and IoC in Spring.

sobes.tech AI

Answer from AI

Dependency Injection (DI) is a pattern where an object's dependencies are provided from outside rather than created internally. This facilitates testing, increases modularity, and improves code manageability.

Inversion of Control (IoC) is a broader principle that means the creation and binding of objects are delegated to an external container or framework, rather than being implemented manually.

In Spring, the IoC container is responsible for creating, configuring, and managing the lifecycle of beans (objects). DI is implemented through:

  • Constructor injection — dependencies are passed via the constructor.
  • Setters — dependencies are set through setter methods.
  • Fields with annotations (@Autowired) — Spring automatically injects dependencies.

Example:

@Component
public class Service {
    private final Repository repo;

    @Autowired
    public Service(Repository repo) {
        this.repo = repo;
    }
}

Here, Spring will create an instance of Repository and pass it to the Service constructor. This makes it easy to change dependency implementations and simplifies testing.

Tell me about the principle of Dependency Injection… - sobes.tech