Creating beans alone is not enough.
They must also be wired together.
That wiring is what Autowiring (DI) does.
What does “wiring” mean?
Connecting beans together by injecting one bean into another.
Car → needs → Engine
@Autowired
Engine engine;
Spring injects the dependency for you.
That is autowiring.
What is @Autowired?
@Autowired tells Spring to automatically inject a required dependency into a Spring Bean.
It is Spring’s way of doing Dependency Injection
When @Autowired is on a setter
@Component
class Car {
private Engine engine;
@Autowired
public void setEngine(Engine engine) {
this.engine = engine;
}
}
You might wonder:
“Who calls this setter? I never call it.”
Spring does.
What happens internally?
When Spring starts:
- Spring creates the Car object using its constructor
- Spring looks for any @Autowired methods
- It finds setEngine(...)
- It looks for an Engine bean
- It finds it in the context
- It calls the setter
- car.setEngine(engineBean);
The dependency is injected
This happens automatically during bean creation.
Beans define which objects Spring manages, and autowiring defines how those objects are connected to each other through dependency injection.
Top comments (1)
Automatically Injection is an opposition of Dependecy Injection. Did you mean Service Locator?