Dependency Injection
Dependency injection is a way to give a class the objects it needs. Spring gives the controller its service instead of the controller making one.
Ask Spring for the service
The field carries @Autowired. Spring fills it before the first request.
@Autowired
private TaskService taskService;The controller uses the filled field
The route calls the service. The controller never calls new.
@GetMapping("/tasks")
public List<Task> tasks() {
return taskService.allTasks();
}Example
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TaskController {
@Autowired
private 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 dependency is an object that a class needs to do its work.
- Injection means Spring hands the object to the class.
- @Autowired marks a field that Spring must fill.
- A bean is an object that Spring keeps and hands out.
- Spring finds a matching bean and sets the field.
- @Component marks a class for Spring to keep as a bean.
- @Service is one kind of @Component.
- @Bean marks a method that makes a bean.
In this example, the controller holds a service field. The field carries @Autowired. Spring fills the field with 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
Field injection is one way, and the next lesson shows a second way.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does @Autowired do?