O'Reilly logo

Dependency Injection: Design patterns using Spring and Guice by Dhanji R. Prasanna

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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; } ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required