Sobes.tech
Junior — Middle

What methods are used to implement dependency injection in the Spring framework?

sobes.tech AI

Answer from AI

Dependency Injection (DI) in the Spring Framework is primarily achieved through three methods:

  1. Constructor Injection — dependencies are passed through the class constructor parameters. This is the most recommended method as it allows creating immutable objects and simplifies testing.

  2. Setter Injection — dependencies are set via setter methods after the object is created.

  3. Field Injection — dependencies are directly injected into class fields using the @Autowired annotation. This method is less preferred due to testing complexity and weak encapsulation.

Example of constructor-based dependency injection:

@Component
public class UserService {
    private final UserRepository userRepository;

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

Spring will automatically create and inject the required UserRepository bean when creating UserService.