What type of injection use by @Autowired?

@Autowired is Spring's dependency injection annotation used to automatically inject required beans into a class. It can be applied to constructors, fields, and setter methods. However, constructor injection is the recommended and most commonly used approach in modern Spring applications because it promotes immutability and makes dependencies mandatory.

Key Points: • @Autowired supports constructor injection, setter injection, and field injection. • Constructor injection is preferred because it ensures required dependencies are available during object creation. • Field injection is simple but less testable and generally discouraged in enterprise applications.

Types of Injection Supported by @Autowired:

1. Constructor Injection (Recommended)

• Dependencies are injected through the constructor. • Supports immutable design using final fields. • Makes dependencies explicit and easy to test.

Code Example:

@Service
public class UserService {

    private final UserRepository userRepository;

    @Autowired
    public UserService(
            UserRepository userRepository) {

        this.userRepository =
                userRepository;
    }
}

2. Setter Injection

• Dependencies are injected through setter methods. • Useful for optional dependencies.

Code Example:

@Service
public class UserService {

    private UserRepository userRepository;

    @Autowired
    public void setUserRepository(
            UserRepository userRepository) {

        this.userRepository =
                userRepository;
    }
}

3. Field Injection

• Spring injects dependencies directly into fields. • Less preferred because it makes unit testing difficult.

Code Example:

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;
}

Which Injection Does Spring Prefer?

Since Spring 4.3: • If a class has a single constructor, Spring automatically uses constructor injection even without @Autowired. • Constructor injection is considered the best practice.

Comparison:

• Constructor Injection - Recommended - Mandatory dependencies - Easy testing - Supports immutability

• Setter Injection - Good for optional dependencies - Dependencies can change later

• Field Injection - Quick and simple - Difficult to test - Not recommended for production code

Interview Tip: A concise interview answer is: @Autowired can be used for constructor, setter, and field injection. Constructor injection is the recommended approach because it ensures mandatory dependencies are provided during object creation, supports immutability, and improves testability. Setter injection is suitable for optional dependencies, while field injection is generally discouraged in modern Spring applications.