Search code examples
javagwtdependency-injectiongwt-gin

Inject entry point class in GWT with GIN


I've tried to do something like this:

@Singleton
public class AAA implements EntryPoint, HistoryListener
{

private BBB bbb;
private CCC ccc;
private DDD ddd;
private EEE eee;

@Inject
public AAA(BBB bbb, CCC ccc, DDD ddd, EEE eee)
{
  this.bbb = bbb;
  this.ccc = ccc;
  this.ddd = ddd;
  this.eee = ee;
}
.........
}

The result is null to all instances.. I expected this way to work...

I know i could do something like this for example

private final MyGinjector injector = GWT.create(MyGinjector.class);

injector.getAAA()
and so on..

Why the first way i have tried does not work for me? Any suggestions?

Thanks


Solution

  • You can use the injectMembers feature of Guice, which in GIN is done by declaring a method in your Ginjector taking a single argument.

    @GinModules(...)
    interface MyGinjector extends Ginjector {
    
       public void injectEntryPoint(AAA entryPoint);
    
       ...
    }
    
    public class AAA implements EntryPoint {
       @Inject private BBB bbb; // field injection works
       private CCC ccc;
    
       @Inject void setCcc(CCC ccc) { this.ccc = ccc; } // and of course method injection
    
       public onModuleLoad() {
          MyGinjector injector = GWT.create(MyGinjector.class);
          injector.injectEntryPoint(this);
          ...
       }
    }
    

    BTW, you don't need to annotate your EntryPoint with @Singleton: unless you inject it into another class (and you'd have to resort to hacks to bind it to the instance created by GWT, and not have GIN create its own), you'll only have a single EntryPoint instance in your app.