How Guy behaves differently as injection types change

Let's 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 commented on annotations 3 @Injectas they are variables here. I wonder how Guice will behave in all three cases (field injections, constructor or setter).

  • Will the instance Granite always be populated with the instance Mineralsconfigured in the module? How does the type of injection (each of 3) affect the instances Granitereturned by the injector, or are they all the same?
  • What if I never explicitly bound Mineralsin the module at all and Minerals the open no-arg constructor was created? For all three injection scenarios, how does Guice create an instance Mineralsto be returned for the requested object Granite?
+3
1
  • Minerals Granite, , " ", , , 1 , , 3 , .
  • Minerals , @Inject, Guice , @Inject(optional = true).
+3

All Articles