Chapter 3. Investigating DI

"The best way to predict the future is to invent it."

—Alan Kay

Previously we discussed two methods of connecting objects with their dependencies. In the main we have written classes that accept their dependencies via constructor. We have also occasionally used a single-argument method called a setter method to pass in a dependency. As a recap, here are two such examples from chapter 1:

public class Emailer {
    private SpellChecker spellChecker;

    public Emailer(SpellChecker spellChecker) {
        this.spellChecker = spellChecker;
    }
}

The same class accepting dependencies by setter:

public class Emailer { private SpellChecker spellChecker; public void setSpellChecker(SpellChecker spellChecker) { this.spellChecker = spellChecker; } ...

Get Dependency Injection: Design patterns using Spring and Guice now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.