3

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!

Michael Laffargue
  • 10,116
  • 6
  • 42
  • 76

2 Answers2

5

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.

Colin Alworth
  • 17,801
  • 2
  • 26
  • 39
0

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.

idle
  • 1,117
  • 9
  • 17
  • See InjectionPoint.getInjectionPoints for the code that actually generates the list of injections which will be run for a class. It looks like it will walk up the type hierarchy injecting fields then methods for each superclass. This means that if you have a Inject method on your class, it will definitely be run after any Inject fields on the class. It is certainly bad practice to rely on this behavior however. (This is in the Guice code, but the Gin generated code is likely similar) – idle Feb 21 '12 at 01:47