Video in progress

Junior 🌱 Spring

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:

  1. By type — for example, beans of type PaymentClient.
  2. If there are several — the one marked @Primary, or the name given in @Qualifier.
  3. 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>.