DEV Community

Likitha Chendrimada Suguna
Likitha Chendrimada Suguna

Posted on

What Happens When You Add '@Autowired' in Spring Boot?

If you have worked with Spring Boot, you have probably seen this:

@Autowired
private UserService userService;
Enter fullscreen mode Exit fullscreen mode

But what actually happens when we write @Autowired?

I used to think Spring just magically creates the object.
There is actually a simple process behind it.

First, What Problem Are We Solving?

Normally in Java, we create objects ourselves:

UserService userService = new UserService();
Enter fullscreen mode Exit fullscreen mode

But in Spring Boot, we don't always create these objects manually.

Instead, Spring manages them for us.

This is where Dependency Injection comes in.

What Does @Autowired Do?

@Autowired tells Spring:

"I need an object of this type here. Please provide one."

For example:

@Service
public class UserService {
}
Enter fullscreen mode Exit fullscreen mode

and:

@RestController
public class UserController {

    @Autowired
    private UserService userService;
}
Enter fullscreen mode Exit fullscreen mode

When the application starts, Spring finds UserService because of @Service.

Spring creates a Bean for it and keeps it inside the Spring IoC container.

Then, when Spring creates UserController, it sees @Autowired and injects the UserService object into it.

So we don't need to write:

new UserService();
Enter fullscreen mode Exit fullscreen mode

The Simple Flow

Think of it like this:

Application starts → Spring scans classes → Creates Beans → Finds @Autowired → Connects the required Bean

That's basically what is happening behind the scenes.

One Thing I Learned

@Autowired is not really about creating objects everywhere.

It is about letting Spring manage objects and their dependencies.

Also, in real projects, constructor injection is generally preferred over field injection:

@RestController
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }
}
Enter fullscreen mode Exit fullscreen mode

The first time I saw this, Spring Boot felt a little magical.

After understanding Dependency Injection and Beans, it started making much more sense.


If you're learning Spring Boot, understanding what happens behind @Autowired is a small step that makes the rest of Spring much easier to understand.

Top comments (0)