IAmYourFaja
IAmYourFaja

Reputation: 56944

How Guice behaves differently as injection types change

Say we have the following code:

public interface Rock {
    // Minerals are a concrete class; omitted for brevity
    public Minerals getMinerals();
}

public class Granite implements Rock {
    // @Inject #1 - field
    private Minerals minerals;

    // @Inject #2 - constructor
    public Granite(Minerals mins) {
        super();
        setMinerals(mins);
    }

    public Minerals getMinerals() {
        return minerals;
    }

    // @Inject #3 - setter
    public void setMinerals(Minerals mins) {
        minerals = mins
    }
}

public class RockModule extends AbstractModule {
    public void configure(Binder guiceBinder) {
        Minerals m = new Minerals(true, 3, MineralEnum.Sedimentary);

        guiceBinder.bind(Minerals.class).toInstance(m);
        guiceBinder.bind(Rock.class).to(Granite.class);
    }
}

public class TestInjections {
    public static void main(String[] args) {
        RockModule mod = new RockModule();
        Injector injector = Guice.createInjector(mod);

        Granite gran = injector.getInstance(Granite.class);
    }
}

I have commented out the 3 @Inject annotations as they are the variables here - I'm wondering how Guice will behave in all 3 cases (field-, constructor- or setter-level injections).

Upvotes: 3

Views: 417

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198471

  1. Minerals will always be injected into the Granite, whichever injection technique you choose, but some injections are "cleaner" than others -- for example, option 1 gives you less control over how the injection is done, and option 3 means your class can't be immutable.
  2. If Minerals isn't bound, lacks a public no-argument constructor, and lacks an @Inject constructor, then Guice throws an exception, unless you use @Inject(optional = true).

Upvotes: 3

Related Questions