Sobes.tech
Junior — Middle

Explain what is meant by dependency injection in software components.

sobes.tech AI

Answer from AI

Dependency Injection (DI) is a design pattern where objects receive their dependencies (such as other objects or services) from outside, rather than creating them themselves.

This allows:

  • Simplifying testing by substituting mocks or stubs for real dependencies.
  • Increasing flexibility and modularity of the code.
  • Reducing component coupling.

In Java, dependency injection is often implemented through constructors, setters, or frameworks (such as Spring), which automatically create and pass the necessary objects.

Example using constructor:

public class Service {
    private final Repository repository;

    // Dependency injection via constructor
    public Service(Repository repository) {
        this.repository = repository;
    }

    public void doWork() {
        repository.save();
    }
}

Here, the Service class does not create a Repository object itself but receives it from outside.

Explain what is meant by dependency injection in… - sobes.tech