Notes
The problem
Here is the problem. The order service creates its own card gateway with new, and checks the real time to apply a happy hour discount at four in the afternoon. To test the discount, you would have to run the test at four o'clock. And every test run charges a real card. The class has quietly decided which gateway and which clock it uses, and nobody outside can change that decision.
class HardWiredOrderService {
CardGateway pay = new CardGateway();
Receipt order(String drink, long p) {
if (LocalTime.now().getHour() == 16)
p = p * 80 / 100; // happy hour
pay.charge(p);
...
}
} The idea
The idea fits in one sentence. A class should ask for the objects it needs, and let someone else create them and pass them in. Those objects are its dependencies: here, a payment gateway and a clock. Injection just means they are handed in from outside instead of built inside with new. The class says what it needs. The caller decides which one. This is the practical tool behind the dependency inversion principle.
- a dependency: an object your
- class needs to do its job
- injection: it is passed in
- from outside, not created
- inside with new
- the class says WHAT it
- needs; the caller decides
- WHICH one
The structure
Here is the new shape. CoffeeOrderService depends on the PaymentGateway interface and on Java's own Clock class. It never mentions CardGateway. Main creates the real card gateway and the system clock, and passes them into the service. The arrows from the service now point at abstractions, and only main knows the concrete choices.
Constructor injection
Constructor injection is the default choice. The dependencies are constructor parameters and are stored in final fields. You cannot create the service without them, so it is never half built. The fields never change after that, which helps with threads. And the constructor shows every dependency at a glance. If it grows to six or seven parameters, that is a useful warning that the class is doing too much.
final class CoffeeOrderService {
private final PaymentGateway pay;
private final Clock clock;
CoffeeOrderService(PaymentGateway pay,
Clock clock) {
this.pay = requireNonNull(pay);
this.clock = requireNonNull(clock);
}
} Setter injection
Setter injection passes a dependency through a setter method after the object is built. Use it only for optional things that have a safe default, like an order listener that does nothing unless someone sets one. The risk is that the object can be used before the setter runs, and the field cannot be final. So keep required dependencies in the constructor, always.
private OrderListener listener =
OrderListener.NONE;
void setListener(OrderListener l) {
this.listener = l;
}
risk: object can be used
before the setter is called Field injection
Field injection lets a framework write directly into a private field, usually marked with an annotation like Autowired in Spring. It is short, which is why it is popular. But the field cannot be final, the dependency is hidden from anyone reading the constructor, and if a test simply calls new on the class, the field is null. Most teams now prefer constructor injection even with a framework.
// needs a DI framework @Autowired private PaymentGateway pay; cannot be final hidden: not in the constructor a plain new in a test leaves the field null
Wiring by hand
Who calls new then? One place near the start of the program, called the composition root. In a small app that is simply main. It creates the real gateway and the system clock, builds the service, and starts work. Everything below main just receives what it needs. You do not need any framework for dependency injection. Plain constructors and one wiring method are enough, and in an interview, this is exactly what you should write.
public static void main(String[] a) {
PaymentGateway pay = new CardGateway();
Clock clock = Clock.systemDefaultZone();
CoffeeOrderService orders =
new CoffeeOrderService(pay, clock);
orders.order("latte", 25000);
} Why tests get easy
Now the payoff. The test builds the same service, but passes a fake gateway that just records what it was asked to charge, and a fixed clock that always says ten past four. It orders a latte for two hundred and fifty rupees and checks that two hundred was charged. The test runs in milliseconds, at any time of day, and never touches a bank. Without injection, this test is impossible to write well.
FakeGateway pay = new FakeGateway();
Clock fourPm = Clock.fixed(
Instant.parse("2026-05-01T16:10:00Z"),
ZoneOffset.UTC);
var s = new CoffeeOrderService(pay, fourPm);
s.order("latte", 25000);
check(pay.charged == 20000); Run it
Follow one call in production. Main asks the service to order a latte. The service asks the injected clock for the time, sees it is happy hour, and takes twenty percent off. It calls charge on the payment gateway interface. At runtime that is the real card gateway, so the bank is charged. The service code is identical in the test. Only the objects passed in are different.
DI containers
What about frameworks? A dependency injection container, like Spring, Guice or Dagger, is simply a tool that creates your objects and passes them into constructors for you, based on annotations or configuration. It saves typing in a big application with hundreds of classes, and manages lifetimes like one instance per app. But it is not the idea itself. The idea is just passing dependencies in.
- Spring, Guice, Dagger and
- Jakarta CDI read annotations
- or config, create objects
- and pass them into
- constructors for you
- useful with hundreds of
- classes; not needed for
- the idea, or in interviews
When not to inject
Do not inject everything. Inject things that touch the outside world or that you may want to swap: payment gateways, repositories, message senders, clocks and random number sources. Plain values and small helpers with no side effects, like a string, a money record or an array list, can just be created with new. Injecting those adds noise with no benefit.
- inject: things that touch the
- outside world or may vary
- gateways, repositories,
- clocks, random, senders
- just new: values and simple
- helpers with no side
- effects: String, Money,
- ArrayList, a record
In interviews
In a machine coding round, give every service its collaborators through the constructor, and build them all in main. Then say why: the parking lot takes its spot strategy, pricing and clock in the constructor, so you can test pricing with a fixed clock. Common mistakes are calling new on a gateway inside a service, using static singletons for everything, or looking dependencies up from a global registry inside each class.
- "ParkingLot takes its spot
- strategy, pricing and clock
- in the constructor, so I
- can test pricing with a
- fixed clock."
- mistakes: new inside the
- service, static singletons
- for everything, a service
- locator in every class