Dependency Injection (DI)

is a design pattern used to achieve Inversion of Control (IoC) between classes and their dependencies. Instead of a class creating its own dependencies, the Spring container injects them at runtime.

In other words It means giving an object its dependencies from the outside, rather than the object creating them itself.

Example Without DI (Tight Coupling):

public class Car {
    private Engine engine = new Engine();  // tightly coupled
}

Example With DI (Loose Coupling):

public class Car {
    private Engine engine;

    public Car(Engine engine) {
        this.engine = engine;
    }
}

Dependency Injection types:

1- Constructor Injection

2- Setter Injection

3- Field Injection

How Spring Knows What to Inject?

Spring uses various annotations and configuration methods to determine what dependencies to inject:

These mechanisms allow Spring to build a dependency graph and resolve what needs to be injected where.

Why Use Dependency Injection?