简体   繁体   中英

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

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.

GIN depends on GWT, so GIN knows about GWT, but GWT does not know about GIN.

So, initializing your classes via GWT.create(AAA.class) will initialize AAA in a normal GWT way, without GIN, meaning no dependency injection.

To have dependency injection you need to initialize your classes through GIN, using injector (as you noted above).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM