What is @Autowired in Spring?

In the Spring Framework, the @Autowired annotation is used for automatic dependency injection. It tells the Spring container to automatically find and inject the required dependency into a class.

Instead of manually creating objects using the new keyword, Spring automatically provides the required object at runtime.

This helps reduce tight coupling between classes and makes applications more flexible and maintainable.




How @Autowired Works

When Spring encounters the @Autowired annotation, it searches for a matching bean in the Spring container and injects it into the required class.

Spring resolves dependencies using type-based injection by default.


Example of @Autowired

Service Class

@Service
class UserService {

    public void getUser() {
        System.out.println("Fetching user details...");
    }
}

Controller Class

@RestController
class UserController {

    @Autowired
    private UserService userService;

    public void displayUser() {
        userService.getUser();
    }
}

Here, Spring automatically injects the UserService object into UserController without manually creating it.


Types of @Autowired Injection

1. Field Injection

@Autowired
private UserService userService;

Spring directly injects the dependency into the field.


2. Constructor Injection

class UserController {

    private UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }
}

This is considered the best practice because it ensures the dependency is always initialized.


3. Setter Injection

@Autowired
public void setUserService(UserService userService) {
    this.userService = userService;
}

Spring injects the dependency using a setter method.


Advantages of @Autowired

1. Automatic Dependency Injection

Spring automatically manages object creation.

2. Reduces Boilerplate Code

Developers do not need to manually instantiate objects.

3. Promotes Loose Coupling

Classes depend on interfaces rather than concrete implementations.

4. Improves Maintainability

Dependencies can be easily changed without modifying business logic.


Conclusion

The @Autowired annotation is one of the most important features in the Spring Framework. It simplifies dependency management by automatically injecting required beans, helping developers build clean, maintainable, and loosely coupled applications.


🚀 Learn Advanced Java System Design

Enhance your backend development and architecture skills with Top System Design with Java Online Training in Hyderabad.


Comments

Popular posts from this blog

How Does HashMap Work Internally in Java?

What is Docker Used for in Java Applications?

Java Future Interface: Complete Practical Guide with Real-Time Examples for Modern Developers (2026)