LOW-LEVEL DESIGN · DESIGN PRINCIPLES · TECHNIQUE · 15 OF 48

Dependency Injection in Java: Constructor, Setter and Field

Stop a class from creating its own collaborators and hand them in instead. Covers constructor, setter and field injection and when to use each, wiring everything by hand in main (the composition root), why injected fakes and a fixed clock make tests fast and exact, and what a DI container adds.

Reported atAccenture
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 14

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 131 lines, with a small main() demo. Save it as DependencyInjectionDemo.java, then run javac DependencyInjectionDemo.java && java DependencyInjectionDemo.

import java.time.Clock;
import java.time.Instant;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * Dependency injection for a coffee order service.
 * Prices are in paise (1 rupee = 100 paise). Happy hour (16:00 to 16:59) takes 20 percent off.
 */
public class DependencyInjectionDemo {

    interface PaymentGateway {
        boolean charge(long paise);
    }

    interface OrderListener {
        OrderListener NONE = (drink, paise) -> { };

        void placed(String drink, long paise);
    }

    record Receipt(String drink, long paise) { }

    /** The real gateway. In production it would call a bank. */
    static final class CardGateway implements PaymentGateway {
        @Override
        public boolean charge(long paise) {
            System.out.println("  [bank] card charged " + paise + " paise");
            return true;
        }
    }

    // ---------- Before: builds its own gateway and reads the real clock ----------

    static final class HardWiredOrderService {
        private final CardGateway pay = new CardGateway();   // cannot be swapped

        Receipt order(String drink, long paise) {
            long price = LocalTime.now().getHour() == 16 ? paise * 80 / 100 : paise;
            pay.charge(price);                                // a test would charge a real card
            return new Receipt(drink, price);
        }
    }

    // ---------- After: dependencies are injected ----------

    static final class CoffeeOrderService {
        private final PaymentGateway pay;                     // constructor injection: required
        private final Clock clock;
        private OrderListener listener = OrderListener.NONE;  // setter injection: optional

        CoffeeOrderService(PaymentGateway pay, Clock clock) {
            this.pay = Objects.requireNonNull(pay);
            this.clock = Objects.requireNonNull(clock);
        }

        void setListener(OrderListener listener) {
            this.listener = Objects.requireNonNull(listener);
        }

        Receipt order(String drink, long paise) {
            boolean happyHour = LocalTime.now(clock).getHour() == 16;
            long price = happyHour ? paise * 80 / 100 : paise;
            if (!pay.charge(price)) {
                throw new IllegalStateException("payment declined");
            }
            listener.placed(drink, price);
            return new Receipt(drink, price);
        }
    }

    // ---------- Test doubles ----------

    static final class FakeGateway implements PaymentGateway {
        final List<Long> charged = new ArrayList<>();
        boolean approve = true;

        @Override
        public boolean charge(long paise) {
            charged.add(paise);
            return approve;
        }
    }

    static void check(boolean ok, String name) {
        System.out.println((ok ? "  PASS " : "  FAIL ") + name);
    }

    /** What a unit test would do: wire fakes instead of real objects. */
    static void runTests() {
        System.out.println("tests:");
        Clock fourPm = Clock.fixed(Instant.parse("2026-05-01T16:10:00Z"), ZoneOffset.UTC);
        Clock nineAm = Clock.fixed(Instant.parse("2026-05-01T09:00:00Z"), ZoneOffset.UTC);

        FakeGateway pay = new FakeGateway();
        new CoffeeOrderService(pay, fourPm).order("latte", 25000);
        check(pay.charged.equals(List.of(20000L)), "happy hour takes 20 percent off");

        FakeGateway pay2 = new FakeGateway();
        new CoffeeOrderService(pay2, nineAm).order("latte", 25000);
        check(pay2.charged.equals(List.of(25000L)), "full price in the morning");

        FakeGateway declining = new FakeGateway();
        declining.approve = false;
        try {
            new CoffeeOrderService(declining, nineAm).order("mocha", 30000);
            check(false, "declined card throws");
        } catch (IllegalStateException e) {
            check(true, "declined card throws");
        }
    }

    /** The composition root: the only place that picks real classes. */
    public static void main(String[] args) {
        System.out.println("production wiring:");
        PaymentGateway pay = new CardGateway();
        Clock clock = Clock.systemDefaultZone();
        CoffeeOrderService orders = new CoffeeOrderService(pay, clock);
        orders.setListener((drink, paise) -> System.out.println("  kitchen: make a " + drink));
        Receipt r = orders.order("cappuccino", 22000);
        System.out.println("  receipt: " + r);

        runTests();

        // The hard-wired version exists only to compare; it would charge a real card in a test.
        System.out.println("hard-wired class: " + HardWiredOrderService.class.getSimpleName());
    }
}

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.

Hard-wired
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.

Dependency injection
  • 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.

Constructor injection
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.

Setter injection
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.

Field injection
// 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.

Composition root
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.

A test with fakes
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.

Containers
  • 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 or new?
  • 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.

Say it like this
  • "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

Interview questions

What is dependency injection?

A technique where an object receives the objects it depends on from outside, usually through its constructor, instead of creating them itself. The caller decides which implementation to use, so the class can be reused and tested with different ones.

Why is constructor injection preferred over field injection?

Constructor injection makes dependencies required and visible, allows final fields so the object is fully built and immutable in its wiring, and works in plain tests with new. Field injection hides dependencies, cannot use final, and leaves fields null without a framework.

When would you use setter injection?

For optional dependencies that have a sensible default, such as a listener or a cache, or to break a rare circular dependency. Required dependencies should still go through the constructor so the object is never used half built.

What is a composition root?

The single place, close to the program entry point, where the object graph is built and real implementations are chosen and wired together. In a small application this is main; in Spring it is the container plus configuration.

How does dependency injection make unit testing easier?

Because the class does not create its collaborators, a test can pass in fakes or stubs, such as a fake payment gateway that records calls or a fixed Clock. Tests become fast, repeatable and free of network, database or time-of-day effects.

What is the difference between dependency injection and dependency inversion?

Dependency inversion is a design principle: high-level code should depend on abstractions, not concrete classes. Dependency injection is a technique for supplying those dependencies from outside. DI is the usual way to put the principle into practice.

Do you need Spring to use dependency injection?

No. Passing dependencies through constructors and wiring them in main is complete dependency injection. A container like Spring or Guice only automates object creation, wiring and lifetimes, which helps in large applications.

Why inject a Clock instead of calling LocalTime.now()?

Time is a hidden dependency on the outside world. Injecting java.time.Clock lets production use the system clock while tests use Clock.fixed, so time-based rules like discounts or expiry can be tested exactly.