Constructor Injection
Constructor injection is dependency injection through a constructor. The controller takes its service as a constructor argument.
Take the service in the constructor
The constructor takes the service. The field keeps it for later.
public TaskController(TaskService taskService) {
this.taskService = taskService;
}Keep the service in a final field
The field is final. Spring sets it once through the constructor.
private final TaskService taskService;Example
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TaskController {
private final TaskService taskService;
public TaskController(TaskService taskService) {
this.taskService = taskService;
}
@GetMapping("/tasks")
public List<Task> tasks() {
return taskService.allTasks();
}
}
@Service
class TaskService {
private final List<Task> tasks = List.of(new Task("Buy milk", false), new Task("Ship Spring Boot", true), new Task("Read a book", false));
public List<Task> allTasks() {
return tasks;
}
}
record Task(String title, boolean done) {
}Key points
- A constructor is a method that makes a new object.
- The constructor takes the service as a parameter.
- Spring calls the constructor and passes the service.
- The field holds the service for later use.
- A final field cannot change after the constructor runs.
- One constructor needs no @Autowired in Spring Boot.
In this example, the controller holds the service in a final field. The constructor takes the service as a parameter. Spring calls the constructor and passes the service. The route answers GET /tasks. The method asks the service for its tasks. The service holds three tasks in memory. The Task record holds a title and a done flag.
Note
Constructor injection is the usual way in Spring Boot.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How does constructor injection give the controller its service?