Sobes.tech
Junior — Middle

How does Spring use dependency injection via constructors?

sobes.tech AI

Answer from AI

Spring uses constructor-based dependency injection to ensure inversion of control and facilitate testing.

When a class declares a constructor with parameters, Spring automatically injects the necessary dependencies, which are also registered in the context, when creating a bean.

Example:

@Component
public class ServiceA {
    private final Repository repository;

    // Constructor with dependency
    public ServiceA(Repository repository) {
        this.repository = repository;
    }

    // class methods
}

Spring, when creating ServiceA, will find the Repository bean and pass it to the constructor. This allows:

  • Making dependencies explicit.
  • Ensuring immutability of fields (final).
  • Simplifying testing by injecting mocks through the constructor.

If the class has only one constructor, Spring uses it automatically. If there are multiple, you can annotate the desired constructor with @Autowired.

Thus, constructor injection is the preferred way to manage dependencies in Spring, providing clean and testable code.

How does Spring use dependency injection via… - sobes.tech