Video in progress
How does @Autowired work?
Spring looks up a bean of the required type in the context and puts it into the constructor, setter or field. If it finds exactly one, it passes it in; if it finds none or several, startup fails.
📖 Answer
@Autowired tells Spring "put a matching bean here". The lookup order:
- By type — for example, beans of type
PaymentClient. - If there are several — the one marked
@Primary, or the name given in@Qualifier. - If it's still ambiguous — the bean whose name matches the parameter or field name.
If nothing is found, the application won't start:
Parameter 0 of constructor in OrderService required a bean of type
'PaymentClient' that could not be found.
That's actually a good thing: the error shows up at startup, not in production.
In a class with a single constructor you don't have to write @Autowired; Spring figures it out. If you need an optional dependency — @Autowired(required = false), Optional<PaymentClient> or ObjectProvider<PaymentClient>.
Sign up to mark studied questions and save your progress.