0
0
SpringbootConceptBeginner · 3 min read

@Autowired in Spring: What It Is and How It Works

@Autowired is a Spring annotation that automatically injects required dependencies into a class. It tells Spring to find and assign the needed object, so you don’t have to create it manually.
⚙️

How It Works

Imagine you have a toolbox and you need a hammer to fix something. Instead of searching for the hammer yourself, you ask a helper who knows exactly where it is and hands it to you. @Autowired works like that helper in Spring. When your class needs another object (a dependency), Spring automatically finds and provides it for you.

This happens because Spring manages all objects (called beans) in a container. When it sees @Autowired on a field, constructor, or setter method, it looks inside the container for a matching bean and injects it. This saves you from writing code to create or find these objects manually.

💻

Example

This example shows a simple service class that needs a repository. Spring injects the repository automatically using @Autowired.

java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
class UserRepository {
    public String getUser() {
        return "Alice";
    }
}

@Component
class UserService {
    private final UserRepository userRepository;

    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public void printUser() {
        System.out.println("User: " + userRepository.getUser());
    }
}

// In a Spring Boot application, UserService will be created with UserRepository injected automatically.
Output
User: Alice
🎯

When to Use

Use @Autowired when you want Spring to automatically provide the objects your class needs. This is common in service classes, controllers, or any component that depends on other beans.

For example, if your service needs to access a database repository or another service, @Autowired saves you from manually creating or passing those objects. It helps keep your code clean and focused on business logic.

Key Points

  • @Autowired injects dependencies automatically from Spring’s container.
  • It can be used on constructors, fields, or setter methods.
  • Helps reduce boilerplate code by letting Spring manage object creation.
  • Requires the target bean to be registered in the Spring context.

Key Takeaways

@Autowired tells Spring to automatically provide required objects to your class.
It works by injecting beans managed inside Spring’s container.
Use it to simplify dependency management and keep code clean.
It can be applied on constructors, fields, or setters.
The injected bean must be registered as a Spring component or bean.