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
@RestControllerpublic class BookController { @Autowired private BookService service; @GetMapping("/books") public List<Book> books() { return service.all(); }}
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.
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
@RestControllerpublic 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)); }}
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.