Frage

I'm a bit lost with the use of Inject on variable.

I got this code working :

private XXServiceAsync xxServiceAsync;

@Inject
protected IndexViewImpl(EventBus eventBus, XXServiceAsync tableManagementServiceAsync) {
    super(eventBus, mapper);

    this.xxServiceAsync = xxServiceAsync;
    initializeWidgets();
}

With this code, I can call my RPC service wherever I need in the class (On click ...) I would like to clear a bit the code by injecting direcly in the variable ; doing so :

@Inject
private XXServiceAsync xxServiceAsync;


protected IndexViewImpl(EventBus eventBus) {
    super(eventBus, mapper);
    initializeWidgets();
}

This always keep the Service to NULL. Am I doing something wrong ? Is the GIN magic with rpc services meant to be done otherwise?

Thanks!

War es hilfreich?

Lösung

It is still null at that point, because Gin (and Guice, and other frameworks like this) cannot assign the fields until the constructor has finished running.

Consider how this would look if you were manually wiring the code (remember that Gin/Guice will cheat a little to assign private fields, call non-visible methods):

MyObject obj = new MyObject();//initializeWidgets() runs, too early!
obj.xxServiceAsync = GWT.create(xxService.class);

If you need something in the constructor, pass it into the constructor. If you wont need it right away (such as until asWidget() is called), then a field or setter annotated with @Inject can be helpful.

Andere Tipps

If you have field level injection you can use an empty @Inject method to do your post-inject initialization. The no-arg injected method will be run after field injections on the class are complete.

@Inject void initialize(){
  ...
  initializeWidgets()
}

Edit: I previously stated that it was run after method injection as well, but testing shows that this is not always the case.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top