AI Hints
Home›Spring Boot Tutorial›@Service, Constructor Injection and @Component and Friends
Spring Boot · Lesson 32 of 120

Constructor Injection

The best way to inject.

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

There's more than one way to inject a dependency. You'll see them all, in real projects. But one of them is clearly the best.

  • Several ways
  • You'll see them all
  • One is best

Field injection

Here, at Autowired sits on a private field. Spring fills the field, after creating the object. It's short, but the field can't be final. And in a test, there's no easy way to pass in a fake service. So it's not recommended.

BookController.javajava
@RestController
public class BookController {

    @Autowired
    private BookService service;

    @GetMapping("/books")
    public List<Book> books() {
        return service.all();
    }
}

Why constructor injection wins

With constructor injection, the field can be final, so it never changes. The object is always complete, the moment it's created. Tests can simply call new, with a fake service. And with only one constructor, you don't even need at Autowired.

keyvalue
final fieldsnever change
Always completenothing missing
Easy testsnew BookController(fake)
One constructorno @Autowired needed

When a bean is missing

What if we forget at Service, on BookService? Then it's not a bean. The controller still asks for one, in its constructor. Run it. The app refuses to start. Spring tells us, the constructor needs a BookService bean, that could not be found. And it even suggests the fix.

BookController.javajava
@RestController
public class BookController {

    private final BookService service;

    public BookController(BookService service) {
        this.service = service;
    }

    @GetMapping("/books")
    public List<Book> books() {
        return service.all();
    }
}
Output
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in BookController required a bean of type 'BookService' that
could not be found.
Action:
Consider defining a bean of type 'BookService' in your configuration.
Also uses Book.java
public record Book(Integer id, String title, String author, double price) {}
Also uses BookService.java
public class BookService {

    public List<Book> all() {
        return List.of(new Book(1, "Dune", "Frank Herbert", 9.99));
    }
}

Summary

Prefer constructor injection, with final fields. If a needed bean is missing, the app fails at startup, with a clear message. Next, at Component, and friends.

Key takeaways
  • Constructor injection
  • final fields
  • Missing bean = clear error
Next up: @Component and Friends — four kinds of beans