Dependency Injection
Dependency injection means a class receives its collaborators from outside instead of constructing them with new or fetching them from a static registry. The dependency arrives through a constructor, a setter or a method parameter, and the class using it never learns which concrete thing it got. The payoff is disproportionate to how unglamorous that is: every dependency a class reaches out for is one your test cannot replace.
💡 Collaborator = another object this one needs to do its job – a repository, a gateway, a clock. Distinct from data, which you pass on each call.
Why this matters: interviewers rarely ask “do you use DI”. They ask “how would you test this”, and in a machine-coding round they read your main: the same question twice. A constructor that opens a database connection cannot be unit-tested at all, and a rule reading LocalDateTime.now() cannot be asserted without waiting for the right hour. Hand in a Strategy, a Repository and an injected Clock, and the design is testable by habit.
Prerequisites
- SOLID Principles – the D is the design rule this technique serves, and this lesson pulls those apart
- Inheritance vs Composition – injection is how a composed object gets its parts
- Testing for Machine Coding – the payoff here is a test, so it lives there
The Problem: the class that builds its own world
This OrderService is complete, correct, and ships orders. It also builds every single thing it depends on:
public class OrderService {
private final OrderRepository repository;
private final EmailSender emailSender;
public OrderService() throws SQLException {
// A database socket, opened in a constructor.
this.repository = new JdbcOrderRepository(
DriverManager.getConnection("jdbc:postgresql://orders-db:5432/orders",
"app", System.getenv("DB_PASSWORD")));
this.emailSender = new SmtpEmailSender("smtp.internal", 25);
}
public Order place(Cart cart, String customerId) {
Order order = new Order(customerId, cart.lines());
// A static singleton lookup, buried mid-method.
PaymentResult result = PaymentGateway.getInstance().charge(order.total());
if (!result.approved()) throw new PaymentDeclinedException(result.code());
// The dependency nobody counts: the machine clock.
LocalDateTime placedAt = LocalDateTime.now();
LocalDate shipDate = placedAt.getHour() >= 18 // after 6pm: tomorrow
? placedAt.toLocalDate().plusDays(1)
: placedAt.toLocalDate();
order.confirm(result.reference(), placedAt, shipDate);
repository.save(order);
emailSender.send(customerId, "Order confirmed", order.summary());
return order;
}
}
OrderService service = new OrderService(); // the test you were going to write
// SQLException: connection refused. No orders-db on a laptop.
Three costs, and the second is the one candidates miss:
- It cannot be unit-tested, and the clock is the worse half. The repository problem is loud: constructing the class opens a TCP connection, so a test needs a live Postgres or a rewrite. The clock problem is quiet – asserting “an order placed after 6pm ships the next day” means running the suite after 18:00, changing the machine’s clock, or skipping the assertion, and teams pick the third. The rule goes untested for years, somebody edits
>= 18to> 18, and nothing turns red.now(),UUID.randomUUID()andMath.random()are all dependencies on something outside the process, in a syntax that looks like arithmetic. - The dependencies are invisible in the signature.
new OrderService()takes no arguments, so learning that this class needs a database, an SMTP host, a gateway and the current time means reading every method – andPaymentGateway.getInstance()sits mid-method, so the constructor alone is not enough. A type signature is the cheapest documentation there is, and this class opted out. - It cannot be reused in a second context. A nightly reconciliation job wants the same placement logic against a read replica, with no email and a fake gateway: no new business logic anywhere, and all of it a change to
OrderService.
The defect is not new; somebody has to call it. The defect is which class calls it: the class that uses a collaborator is the worst place to decide which collaborator it uses.
The three forms of injection
Constructor injection – new OrderService(repository, clock) – is the default. Fields can be final, buying immutability and safe publication across threads (Immutability and Equality); a requireNonNull check runs once, so an OrderService that exists is one that works; the dependency list sits in one signature, read before any method body; and a circular dependency fails loudly at wiring time instead of producing two objects pointing at each other’s unfinished selves. A growing parameter list is useful feedback rather than a problem.
Setter injection – service.setAuditSink(sink) – is for a genuinely optional collaborator, and the cost is what the type system can no longer promise: the field cannot be final, and between construction and the setter the object exists in a state it should not be used in. Its one honest argument is a collaborator whose absence leaves the object working, such as a metrics sink or a debug tracer. Default the field to a no-op rather than to null.
💡 No-op or null object = an implementation that satisfies the interface and does nothing, so callers need no null check.
Method injection – quote(cart, discountPolicy) – hands the dependency to the call that needs it, and is right when the dependency varies per call rather than per object: a Comparator for one sort, a DiscountPolicy for one quote. Making that a field is the real error, since you would store something belonging to a single call and the object stops being safe to share.
Field injection – a container reflecting into a private @Inject field, with no constructor at all – has no honest argument: it reintroduces cost (2) exactly, and only the framework can construct the class, so new OrderService(...) in a test is impossible.
Real-World Example: Order Service with a Composition Root
import java.time.*;
import java.util.*;
public class OrderService {
private final OrderRepository repository;
private final PaymentGateway payments;
private final Clock clock; // java.time.Clock -- the whole lesson
private final EventPublisher events;
public OrderService(OrderRepository repository, PaymentGateway payments,
Clock clock, EventPublisher events) {
this.repository = Objects.requireNonNull(repository, "repository");
this.payments = Objects.requireNonNull(payments, "payments");
this.clock = Objects.requireNonNull(clock, "clock");
this.events = Objects.requireNonNull(events, "events");
}
public Order place(Cart cart, String customerId) {
// now(clock), not now(). That argument is the whole difference.
LocalDateTime placedAt = LocalDateTime.now(clock);
Order order = new Order(customerId, cart.lines(), placedAt);
PaymentResult result = payments.charge(customerId, order.total());
if (!result.approved()) throw new PaymentDeclinedException(result.code());
order.confirm(result.reference(), shipDateFor(placedAt));
repository.save(order);
events.publish(new OrderPlaced(order.id(), placedAt));
return order;
}
// The rule under test: placed at or after 18:00 means it ships tomorrow.
private LocalDate shipDateFor(LocalDateTime at) {
return at.getHour() >= 18 ? at.toLocalDate().plusDays(1) : at.toLocalDate();
}
}
// THE COMPOSITION ROOT. One place builds the object graph; nothing below it
// builds its own collaborators. The only file naming JDBC, Stripe or Kafka.
public final class Main {
public static void main(String[] args) {
OrderService orders = new OrderService(
new JdbcOrderRepository(PooledDataSource.from(Config.fromEnv())),
new StripePaymentGateway(Config.stripeKey()),
Clock.systemDefaultZone(), // the real clock, named once
new KafkaEventPublisher("orders.v1"));
orders.place(Cart.of(new LineItem("SKU-1041", 2)), "CUST-91");
}
}
// The payoff: no database, no waiting until evening.
class OrderServiceTest {
private static final ZoneId IST = ZoneId.of("Asia/Kolkata");
private static final Cart CART = Cart.of(new LineItem("SKU-1041", 1));
private static OrderService serviceAt(int hour, int minute) {
Clock frozen = Clock.fixed(LocalDateTime.of(2026, 11, 12, hour, minute)
.atZone(IST).toInstant(), IST);
return new OrderService(new InMemoryRepo(), new ApprovingGateway(),
frozen, new RecordingPublisher());
}
@Test
void sixPmIsTheBoundary() {
assertEquals(LocalDate.of(2026, 11, 12),
serviceAt(17, 59).place(CART, "C-91").shipDate());
assertEquals(LocalDate.of(2026, 11, 13),
serviceAt(18, 0).place(CART, "C-91").shipDate());
}
// The whole fake. No schema, no container image to pull.
static final class InMemoryRepo implements OrderRepository {
private final Map<String, Order> saved = new LinkedHashMap<>();
@Override public void save(Order order) { saved.put(order.id(), order); }
}
}
from datetime import date, datetime, timedelta, timezone
from typing import Callable, Protocol
class OrderRepository(Protocol):
"""Protocol, not ABC: a fake satisfies the checker without inheriting."""
def save(self, order: "Order") -> None: ...
Clock = Callable[[], datetime] # a callable, not a one-method class
class OrderService:
def __init__(
self,
repository: OrderRepository,
payments: "PaymentGateway",
events: "EventPublisher",
clock: Clock = lambda: datetime.now(timezone.utc),
) -> None:
# Parameters with defaults are the pragmatic Python idiom: production
# callers never mention the clock and tests always can.
self._repository, self._payments = repository, payments
self._events, self._clock = events, clock
def place(self, cart: "Cart", customer_id: str) -> "Order":
placed_at = self._clock()
order = Order(customer_id, cart.lines, placed_at)
result = self._payments.charge(customer_id, order.total)
if not result.approved:
raise PaymentDeclined(result.code)
ships = placed_at.date() + timedelta(days=1 if placed_at.hour >= 18 else 0)
order.confirm(result.reference, ships)
self._repository.save(order)
self._events.publish(OrderPlaced(order.id, placed_at))
return order
def test_after_six_pm_ships_next_day() -> None:
frozen = datetime(2026, 11, 12, 18, 30, tzinfo=timezone.utc)
service = OrderService(InMemoryRepo(), ApprovingGateway(),
RecordingPublisher(), clock=lambda: frozen)
cart = Cart([LineItem("SKU-1041", 1)])
assert service.place(cart, "C-91").ship_date == date(2026, 11, 13)
# THE TEMPTATION, and why it is the worse trade:
# with mock.patch("shop.orders.datetime") as fake: # DON'T
# fake.now.return_value = frozen
# patch() rebinds a name inside a module, so the test now asserts on the
# implementation's import path: move the function or call time.time() instead,
# and the test breaks although the behaviour did not.
#include <chrono>
#include <functional>
#include <memory>
using TimePoint = std::chrono::system_clock::time_point;
// A one-method interface is better expressed as a callable. Held by value, so
// no lifetime question arises for this dependency at all.
using Clock = std::function<TimePoint()>;
class OrderService {
// OWNERSHIP. shared_ptr says "I keep this alive as long as I live", so the
// dependency cannot die before I do. A reference member -- `const
// OrderRepository& repository_;` -- instead says "the caller owns this and
// guarantees it outlives me": fine when a composition root builds the graph
// in main, a dangling reference the moment this object outlives it.
std::shared_ptr<OrderRepository> repository_;
std::shared_ptr<PaymentGateway> payments_;
Clock clock_;
public:
OrderService(std::shared_ptr<OrderRepository> repository,
std::shared_ptr<PaymentGateway> payments, Clock clock)
: repository_(std::move(repository)), payments_(std::move(payments)),
clock_(std::move(clock)) {}
Order place(const Cart& cart, const std::string& customerId) {
const TimePoint placedAt = clock_(); // not system_clock::now()
Order order(customerId, cart.lines(), placedAt);
const PaymentResult result = payments_->charge(customerId, order.total());
if (!result.approved) throw PaymentDeclined(result.code);
order.confirm(result.reference, shipDateFor(placedAt));
repository_->save(order);
return order;
}
};
// The composition root is also the lifetime root. A test passes
// `[frozen] { return frozen; }` as the clock -- the whole test double.
int main() {
OrderService orders(std::make_shared<SqliteOrderRepository>("orders.db"),
std::make_shared<StripePaymentGateway>(stripeKeyFromEnv()),
[] { return std::chrono::system_clock::now(); });
std::vector<LineItem> lines;
lines.push_back(LineItem{"SKU-1041", 2});
orders.place(Cart{lines}, "CUST-91");
}
The composition root, and why you do not need Spring
💡 Composition root = the single place in an application that constructs the object graph. Everything below it receives its collaborators and constructs none of them.
That is the lesson’s spine, so here it is as a rule you can enforce: exactly one region of code calls new on infrastructure classes, and it sits as close to the process entry point as possible – a main, a Bootstrap, a @Configuration class. The audit is a grep for new JdbcOrderRepository, which should only hit the root. It also answers the objection people raise first, “but someone says new”: you gained one file allowed to know about databases instead of thirty that should not.
Manual DI is DI. A container is a labour-saving device for an application with hundreds of classes and several object lifetimes, not the thing that makes the design work. In a 90-minute machine-coding round, constructor parameters plus one wiring block in main is correct, complete, and better, since the interviewer reads the graph in fifteen lines. “I’d use Spring and inject it” is a non-answer to someone who asked for a design.
Four ways this goes wrong in practice
A Service Locator is not the fix. It replaces new JdbcOrderRepository(...) with ServiceLocator.get(OrderRepository.class), which lets a test register a fake first and leaves cost (2) fully intact: the constructor still takes no arguments, so learning what the class needs still means reading all of it. It also makes a missing registration a run-time NullPointerException rather than a constructor you cannot call, and because the locator is global mutable state, one test that forgets to reset leaks its fake into the next. It is legitimate only where you do not control construction – a servlet container or a deserialization callback builds your class for you, and there it beats a hard-coded new.
Eight constructor parameters is a message, not an inconvenience. The instinct is to hide the count with field injection, a “context” object or a builder, and all three treat the symptom: the list measures how many things the class coordinates, and eight says it absorbed three responsibilities. Extract a collaborator instead – if OrderService also takes a tax calculator and a currency converter, pricing is a separate object holding those and OrderService takes PricingService: one fewer parameter, one more testable class. That is the Single Responsibility Principle being measurable for once, which is why SOLID Principles and this lesson are one conversation from two directions, and why a Builder fits optional data and not required collaborators.
Not everything is a candidate. Injection is for collaborators – things with behaviour you might legitimately replace. Value objects and data are not: Money and a Cart go to the method that uses them, and injecting Money is nonsense, yielding a service that can only ever price one amount. Configuration is not either: a String apiKey in a constructor is config rather than DI, and the tell is that nobody would write a fake String. Nor is anything part of the object’s identity, like the HashMap inside an LRU cache, where nobody wants a different one and exposing it lets a caller mutate your internals. There new is correct, and injecting anyway is over-engineering.
An interface per injected class is not the rule. Extracting OrderServiceInterface for OrderService gives you a codebase where every type has one implementation and every “go to definition” lands on an empty declaration. Inject the concrete class when there is one implementation substitutable enough to fake, such as a non-final class you can subclass. Add the interface when a second implementation actually exists, or the dependency crosses a boundary you must control in a test: database, network, clock, random source, the four that always pay. And the Dependency Inversion Principle decides where that file goes – beside the consumer, which is Repository Pattern in one case.
Dependency Injection vs Dependency Inversion vs Inversion of Control vs a DI container
These four get used interchangeably and three of the four usages are wrong. They are different kinds of thing: a principle, a category, a technique, and a product.
| Term | What it actually says | Kind of thing | Tell |
|---|---|---|---|
| Dependency Inversion Principle | Depend on an abstraction owned by the consumer, not the implementor | A design rule about which way the arrows point | The interface file sits in the package that uses it: OrderService declares OrderRepository, the JDBC package implements it |
| Inversion of Control | The framework calls your code rather than the reverse | A broad category, not a technique | You wrote a method you never call. A Template Method hook, an Observer callback and a servlet all qualify, no injection anywhere |
| Dependency Injection | A component receives its collaborators from outside rather than building or locating them | One technique, serving the two above | The collaborator appears in a signature – constructor, setter or parameter – satisfiable by hand in one line |
| A DI container | Wiring is automated from annotations or a module class | A tool, and optional | Delete Spring and a DI design still compiles with a longer main |
The relationships are strictly nested, and that is what an interviewer is listening for: DI is one way to achieve IoC over your dependencies, IoC is the general category, DIP is the principle saying what to depend on, and a container is tooling that performs DI for you. A Factory returning an interface satisfies DIP with no injection; a template method is IoC with no DI; and Spring violates DIP happily when you inject JdbcOrderRepository directly, which is how most “we use DI” codebases keep the arrows pointing the original way.
When to Inject vs When to Just Construct It
| Inject When | Construct It Inline When |
|---|---|
| It touches the outside world – database, network, filesystem, clock, random source | It is a value object or data – Money, a LocalDate, a request you were handed |
| Behaviour must vary by context – real gateway in production, fake in tests, replica in a batch job | It is part of the object’s identity – the ArrayList in a Cart, the HashMap in a cache |
| It is expensive or shared and must exist once per process – a connection pool, a thread pool | It is pure, with no I/O and no clock – a formatter, a comparator, a validator |
| The dependency is worth advertising in the signature as documentation | You are in the composition root or a Factory, whose job is building |
| It is a Strategy the caller is meant to choose | No test or environment would want a different one – see over-engineering |
The characteristic failure mode is pass-through injection: a parameter threaded through four constructors so the class at the bottom can have it. Main injects a Clock into CheckoutFacade, which passes it to OrderService, which passes it to ShippingCalculator – the only object that calls now(). Three classes now list a dependency they never use, and changing the bottom one’s needs edits all four. Either let the composition root build ShippingCalculator and inject that, or pass the timestamp as a method parameter. The second generalises: a dependency you can turn into a parameter is no longer a dependency.
Interview Questions
-
“What is the difference between dependency injection, the dependency inversion principle, and inversion of control?” – Three kinds of thing, nested. DIP is a design rule: depend on an abstraction that belongs to the consumer, so
OrderRepositoryships withOrderService. IoC is a category – the framework calls you rather than the reverse, which a template method and a callback also satisfy with no injection in sight. DI is one technique serving both, where the collaborator arrives through a signature instead of being constructed or located, and a container is a tool that automates the wiring: the optional part. -
“Why constructor injection over field injection?” – Fields can be
final, so the object is immutable and safely publishable across threads; a half-built object becomes impossible; and the whole dependency list sits in one signature, sonew OrderService(...)works in a test with no framework running, while a field-injected class can only be built by its container. Field injection is popular because it hides the dependency count – exactly the number you want visible. -
“How do you test code that calls
LocalDateTime.now()orUUID.randomUUID()?” – You stop calling them and inject the capability: aClockand anIdGenerator, real ones wired inmain, fixed ones in the test.Clock.fixed(...)turns “orders after 6pm ship next day” from an assertion you can only run in the evening into two ordinary unit tests at 17:59 and 18:00. Recognise it as a general move, since it is the real question behind half of “how would you test this”: find the hidden call to something outside the process and make it an argument. -
“Is a Service Locator acceptable?” – At a boundary where you do not control construction, yes: a servlet container or a deserialization callback builds your class for you, and
ServiceLocator.get(...)beats a hard-codednew. For your own classes, no, and the reason is precise – it fixes testability only partly while leaving the dependency invisible in the signature, so you still cannot learn what a class needs without reading all of it. -
“Do you need an interface for everything you inject?” – No, and reflexively extracting one per class gives you a codebase where every type has a single implementation and every navigation lands on an empty declaration. Inject the concrete class when one implementation is substitutable enough to fake, and add the interface when a second one exists or the dependency crosses a boundary you must control in a test. Put that file in the consumer’s package, since an interface extracted from the JDBC class has inverted nothing.
See It in Action
- Task Scheduler – an injected
Clocktests “runs every 5 minutes” instantly instead of sleeping - Circuit Breaker – the half-open transition is time-based, so an injected clock makes the state machine testable
- Movie Ticket Booking – seat hold expiry needs a clock and payment a gateway, both faked
- URL Shortener – an injected
IdGeneratorandKeyValueStoretest encoding without Redis