SPRING CONCEPTS

Dependency injection

Spring Concepts / Dependency injection

Dependency injection supplies an object with the collaborators it needs.

Understand the idea

Constructor injection expresses required collaborators as constructor arguments. A single constructor does not need @Autowired in these Spring classes. A final field keeps the reference stable. Tests can pass a mock without starting the application.

A concrete example

public TodoService(TodoRepository repository) {
    this.repository = repository;
}

In the application

TodoController receives TodoService; TodoService receives TodoRepository. Neither creates its collaborator with new.

A manually constructed object is not automatically configured like a bean managed by the Spring container.

Detailed walkthrough: How Spring creates and connects objects →

See it in a working stage

Related concepts

Read the official documentation ↗
Java 21 · Spring Boot 4.1.1 · Edupoly