@Autowired is a Spring annotation used for dependency injection. It automatically wires a bean (object) into another bean by matching types.

Purpose

  1. Simplify Dependency Injection:
    No need for explicit bean configuration in XML or Java; Spring does it for you.

  2. Automatic Wiring:
    Spring looks for a matching bean in the application context and injects it where needed.

Example

@Component
class Car {
    @Autowired
    private Engine engine; // Spring injects Engine bean here
}

Notes

  • If multiple beans match, you can use @Qualifier to specify which one.
  • For optional dependencies, use required = false:

    @Autowired(required = false)
    private Engine engine;