Sobes.tech
Middle

What dependency injection methods are available in Spring? Which is preferred?

sobes.tech AI

Answer from AI

Dependency Injection (DI) in Spring can be implemented in three main ways:

  1. Through constructor — dependencies are passed via constructor parameters. This allows creating immutable objects and simplifies testing.

  2. Through setters — dependencies are set via setter methods after object creation.

  3. Through field injection — dependencies are directly injected into class fields using annotations.

Constructor injection is preferred because it provides:

  • Explicit declaration of all dependencies
  • Immutability of the object after creation
  • Ease of testing and maintaining the code

Example of constructor injection:

@Component
public class Service {
    private final Repository repository;

    @Autowired
    public Service(Repository repository) {
        this.repository = repository;
    }
}
What dependency injection methods are available in… - sobes.tech