Video in progress

Strong Junior 🌱 Spring

Why don't you need @Autowired on a class with a single constructor?

Since Spring 4.3, if there's only one constructor, Spring just uses it. You only need @Autowired when there are several constructors, to tell Spring which one to pick.

📖 Answer

@Service
public class InvoiceService {
    private final InvoiceRepository invoices;
    private final Clock clock;

    public InvoiceService(InvoiceRepository invoices, Clock clock) { // no @Autowired needed
        this.invoices = invoices;
        this.clock = clock;
    }
}

When Spring creates a bean, it has to know which constructor to call. With one constructor there's nothing to decide. With two constructors and no @Autowired on either, Spring looks for a no-arg constructor; if that's missing too, startup fails.

That's why with Lombok people often write this:

@Service
@RequiredArgsConstructor
public class InvoiceService {
    private final InvoiceRepository invoices;
    private final Clock clock;
}

@RequiredArgsConstructor generates a single constructor from all the final fields. The code is shorter, but it's still the same constructor injection.