Search code examples
javagwtdependency-injectiongwt-gin

How to propagate a value during injection with GIN


I want to inject a class A somewhere with GIN. The A class constructor requires an id know at runtime plus two other classes B and C. B and C constructors requires the same id of A as parameters.

Here a example of the classes.

public class A {
   @Inject
   public A(String id, B b, C c)
   {
    ...
   }
}

public class B {
   @Inject
   public B(String id)
   {
    ...
   }
}

public class C {
   @Inject
   public C(String id)
   {
    ...
   }
}

How can I propagate the id to all the classes during A injection?

One solution is to use an AssistedInjectionFactory with a creation method for all the three classes, but this requires to modify the A constructor in order to use the factory to instantiate B and C.

There are other ways to use GIN and avoid the A constructor boilerplate code?


Solution

  • I would use @Named annotation, and depending on how you want to compute the id value, the bindConstant method or a Provider:

    ...
    @Inject public A(@Named("myId") String id, B b, C c)
    ...
    @Inject public B(@Named("myId") String id)
    ...
    @Inject public C(@Named("myId") String id)
    
    
    public class MyModule extends AbstractGinModule {
    
      protected void configure() {
        // You can use bindConstant and compute the id in configure()
        String myid = "foo_" + System.currentTimeMillis();
        bindConstant().annotatedWith(Names.named("myId")).to(myId)
      }
    
      // Or you can use a provider to compute your Id someway 
      @Provides @Named("myId") public String getMyId() {
        return "bar_" + System.currentTimeMillis();
      }      
    
    }