Phoenix
Phoenix

Reputation: 8923

Dependency injection in Guice

public class N extends R {

    private final A a;
    private B b;

    @Inject
    N(@Assisted final A a, final B b) {
        a= a;
        b= b;
    }
}

My understanding of this is the parameter "a" I'll be providing and the Guice dependency injector will take care of injecting "b" correct ? Do I need to add any annotations for guice being able to inject "b", how do I inject "b" ?

Upvotes: 0

Views: 96

Answers (1)

condit
condit

Reputation: 10962

Guice is going to inject B based on how you configure it in your Module. You don't need to add anything else other than @Inject (which you already have). Here's a more complete example building on your class:

public class GuiceExample {

  static class N {
    private final A a;
    private B b;

    @Inject
    N(@Assisted final A a, final B b) {
      this.a = a;
      this.b = b;
    }
  }

  static class A {}
  static class B {}

  static interface NFactory {
    public N create(A a);
  }

  static class Module extends AbstractModule {
    @Override 
    protected void configure() {
      install(new FactoryModuleBuilder().implement(A.class, A.class).build(NFactory.class));
      bind(B.class); // Or however you want B to be bound...
    }
  }

  @Test
  public void test() {
    Injector i = Guice.createInjector(new Module());
    N n = i.getInstance(NFactory.class).create(new A());
  }

}

You should bind B in your configure method as you see fit. And you would inject NFactory into the class where you need to produce Ns from As.

Upvotes: 3

Related Questions