designpatterns java

“Dependency Injection” is a 25-dollar term for a 5-cent concept.Dependency injection means giving an object its instance variables.” - James Shore: Dependency Injection Demystified

Inversion of Control Containers and the Dependency Injection pattern

Fundamentals

Inversion of Control (IoC)

Inversion of Control | Baeldung on Computer Science

Inversion of Control (IoC) is a design principle where the control of object creation and dependency management is transferred from the class itself to an external entity (e.g., a framework or container).

  • Without IoC: A class creates its own dependencies (Tightly Coupled).
  • With IoC: Dependencies are provided externally, making the class loosely coupled and more flexible.

IoC is a broader concept, where the framework controls object creation and flow.
Dependency Injection (DI) is a way to achieve IoC, where dependencies are injected rather than created inside the class.

DIP

Transclude of af01.6---dependency-inversion-principle-(dip)

DI

Dependency Injection(DI) Design Pattern - GeeksforGeeks

Dependency injection (DI) is a design pattern that decouples classes from their dependencies by externalizing their creation and management. Instead of a class constructing its dependencies directly.

Core Concepts:

  • Decoupling
  • Testability
  • Reusability
classDiagram
    class Engine {
        <<interface>>
        +start() void
    }

    class PetrolEngine {
        +start() void
    }

    class DieselEngine {
        +start() void
    }

    class Car {
        -Engine engine
        +Car(Engine engine)
        +drive() void
    }

    Engine <|-- PetrolEngine
    Engine <|-- DieselEngine
    Car --> Engine : "Dependency Injection"

Types of DI

  1. Constructor Injection
  2. Setter Injection
  3. Interface Injection

In Dependency Injection (DI):

  • Use setter injection when the dependency is optional.
  • When the dependency is required, there is no point in using setter injection.

Example

Without DI(Tightly Coupled):

Class Car {
	private Engine engine = new PetrolEngine();
	
	// Rest of the code..
}

With DI:

Class Car {
	// Inject an Instance of Engine (dependency of car) at runtime
	private Engine engine;
	// Construter Injection
	Car(Engine engine) {
		this.engine = engine;
	}
 
	// OR we can use Setter Injection
	void setEngine(Engine engine) {
		this.engine = engine
	}
}

Spring Boot - Dependency Injection