DEV Community

Phoenix
Phoenix

Posted on

Beans using Autowiring

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
Enter fullscreen mode Exit fullscreen mode
@Autowired
Engine engine;
Enter fullscreen mode Exit fullscreen mode

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
vpospichal profile image
Vlastimil Pospíchal • Edited

Automatically Injection is an opposition of Dependecy Injection. Did you mean Service Locator?