AI Hints
Home›Spring Boot Tutorial›Inversion of Control, Beans and Dependency Injection
Spring Boot · Lesson 30 of 120

Dependency Injection

Spring passes what you need.

⏱ 2 min read▶ Video at 39:24🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

Our controller shouldn't do everything itself. It should ask another object, a service, for the books. But how does the controller get the service?

  • Controllers shouldn't do it all
  • Ask a service
  • How to get it?

Dependency injection

A dependency is an object your class needs, to do its job. The controller declares it, as a constructor parameter. Spring sees the parameter, and finds a bean of that type. It creates the service first. Then it passes the service into the controller's constructor.

  1. Controller needs a BookService
  2. Declared in the constructor
  3. Spring finds that bean
  4. Creates the service first
  5. Passes it in

BookService.java

At Service makes this class a bean too. The constructor prints a message, so we can see when it's created. And titles returns the list of books.

BookService.javajava
@Service
public class BookService {

    public BookService() {
        System.out.println("Spring created a BookService");
    }

    public List<String> titles() {
        return List.of("Dune", "Circe");
    }
}

Injected for us

The controller keeps the service in a final field. Its constructor asks for a BookService. We never call new. Spring passes it in. The endpoint just asks the service for titles. Run it. The service is created first, then the controller, with that service. And the request returns the service's titles.

BookController.javajava
@RestController
public class BookController {

    private final BookService service;

    public BookController(BookService service) {
        System.out.println("Spring created a BookController, with a service");
        this.service = service;
    }

    @GetMapping("/books")
    public List<String> books() {
        return service.titles();
    }
}
Output
["Dune","Circe"]

── app log ──
Spring created a BookService
Spring created a BookController, with a service
Also uses BookService.java
@Service
public class BookService {

    public BookService() {
        System.out.println("Spring created a BookService");
    }

    public List<String> titles() {
        return List.of("Dune", "Circe");
    }
}
Also uses _curl.sh
curl localhost:8080/books

Summary

Dependency injection means Spring passes each object the beans it needs, through its constructor. Next, a closer look at services.

Key takeaways
  • A dependency is a need
  • Ask in the constructor
  • Spring passes it
Next up: @Service — where the logic lives