Dependency Injection

Supplying an object's dependencies from outside — constructor, setter and interface injection, the composition root, DI containers (Spring, Guice, FastAPI, NestJS), scopes, and testing with fakes.

Intermediate 2 min readLesson 22 of 24 Interview Q&A

Dependency injection (DI) means an object receives the objects it depends on instead of creating or looking them up itself. It's the most practical way to apply the dependency inversion principle, and it's what makes code testable.

Without DI
Java
class OrderService {
    private final OrderRepository repo =
        new PostgresOrderRepository(
            "jdbc:postgresql://prod/db");
    private final EmailSender mail =
        new SmtpEmailSender("smtp.prod");
}
  • Hard-wired to Postgres and SMTP
  • Tests hit a real database and send real email
  • Configuration buried inside the class
With DI
Java
class OrderService {
    private final OrderRepository repo;
    private final EmailSender mail;

    OrderService(OrderRepository repo,
                 EmailSender mail) {
        this.repo = repo;
        this.mail = mail;
    }
}
  • Depends only on interfaces
  • Tests pass in-memory fakes
  • Wiring happens in one place

Three forms

FormHowUse
Constructor injectionDependencies are constructor parametersDefault choice: dependencies are explicit, required, and can be final/immutable
Setter / property injectionSet after constructionOptional dependencies; circular cases (a smell)
Method injectionPassed to the method that needs itVaries per call (a request context, a clock)

Field injection (@Autowired private Repo repo;) is convenient but hides dependencies and prevents immutability; prefer constructors.

The composition root

Somewhere, someone must create the real objects. Do it in one place at application start-up — the composition root (main, the app factory) — and nowhere else.

// Manual DI: perfectly fine for small and medium apps
public class Main {
    public static void main(String[] args) {
        Config cfg = Config.fromEnv();
        DataSource ds = Hikari.create(cfg.dbUrl());
        OrderRepository repo = new JdbcOrderRepository(ds);
        EmailSender mail = new SmtpEmailSender(cfg.smtpHost());
        Clock clock = Clock.systemUTC();
        OrderService orders = new OrderService(repo, mail, clock);
        new HttpServer(new OrderController(orders)).start(cfg.port());
    }
}

DI containers

In large applications, manual wiring of hundreds of objects gets tedious. A DI container (IoC container) builds the object graph for you: you declare components and their dependencies; it figures out the construction order, creates them, and manages their lifetimes.

// Spring: classes are discovered and wired by type
@Repository
class JdbcOrderRepository implements OrderRepository { JdbcOrderRepository(DataSource ds) {...} }

@Service
class OrderService {
    private final OrderRepository repo;
    private final EmailSender mail;
    OrderService(OrderRepository repo, EmailSender mail) {   // constructor injection, no annotation needed
        this.repo = repo; this.mail = mail;
    }
}

@Configuration
class InfraConfig {
    @Bean Clock clock() { return Clock.systemUTC(); }       // explicit factory for third-party types
}

Scopes (lifetimes)

ScopeOne instance per…Typical use
SingletonApplicationStateless services, connection pools, clients
Request / scopedHTTP requestDatabase session/unit of work, current user
Transient / prototypeInjectionLightweight, stateful helpers

Testing is the payoff

@Test
void placingAnOrderSendsConfirmation() {
    var repo = new InMemoryOrderRepository();
    var mail = new RecordingEmailSender();
    var clock = Clock.fixed(Instant.parse("2025-01-01T00:00:00Z"), ZoneOffset.UTC);
    var service = new OrderService(repo, mail, clock);

    service.place(new Order("o1", "alice@example.com"));

    assertThat(repo.find("o1")).isPresent();
    assertThat(mail.sent()).containsExactly("alice@example.com");
}

Notice the clock: time, randomness and environment variables are dependencies too. Injecting them makes tests deterministic.

Service locator: the anti-pattern cousin

A service locator is a global registry objects query: Registry.get(EmailSender.class). It decouples from concrete classes, but hides dependencies (you must read the code to know what a class needs) and makes tests depend on global setup. Prefer injection.

Key takeaways
  • DI: objects receive dependencies instead of creating them.
  • Prefer constructor injection: explicit, required, immutable.
  • Wire everything in one composition root; manual DI is fine for small apps.
  • Containers (Spring, Guice, FastAPI Depends, NestJS) automate wiring and manage scopes.
  • Avoid captive dependencies and service locators; inject clocks and randomness for deterministic tests.
Interview questions
QWhat is inversion of control?easy

A design where a framework or container, rather than your code, controls the flow or the creation of objects. Dependency injection is one form: instead of a class constructing its collaborators, the container (or composition root) constructs and supplies them. Template methods and callbacks are other forms ("don't call us, we'll call you").