CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 3 of 6 · 1 min read

Constructor injection

The default way to inject.

The usual form is constructor injection. Every dependency is a constructor parameter, stored in a final field.

interface Clock      { long now(); }
interface Notifier   { void notify(String to, String msg); }
interface BookingStore { void save(String id, long when); int count(); }

class BookingService {
    private final Clock clock;
    private final Notifier notifier;
    private final BookingStore store;

    BookingService(Clock c, Notifier n, BookingStore s) {
        clock = Objects.requireNonNull(c);
        notifier = Objects.requireNonNull(n);
        store = Objects.requireNonNull(s);
    }

    void book(String user) {
        store.save(user, clock.now());
        notifier.notify(user, "booked at " + clock.now());
    }
}

The constructor signature lists everything the class needs. A reader sees the dependencies at once, and no hidden new or global is used inside. The requireNonNull calls fail early if a caller forgets one. Passing null for all three throws a NullPointerException at once, and does not cause a failure later in book.

Another form is setter injection, where the object is made first and the dependencies are set afterwards. CC mentions it next to constructor arguments. The object can be used before all setters are called, which is the same inconsistency problem as the JavaBeans style (module 3). Constructor injection is the default choice in new code.

Check yourself: 1. Why are the fields final? 2. What happens with new BookingService(null, null, null)? 3. Why is setter injection weaker?