Issue
I am trying to do dependency injection in a javaFX project.
I have a
@Singleton
public class WidgetFactory implements IWidgetFactory
My public class ZentaEditorModule extends MvcFxModule
contains
@Override
protected void configure() {
super.configure();
//some other code
System.out.println("binding WidgetFactory");
bind(IWidgetFactory.class).to(WidgetFactory.class);
}
In my public class ZentaApplication extends Application
I have this, running in application initialization:
final Injector injector = Guice.createInjector(module);
System.out.printf(
"widgetFactory=%s\n", injector.getInstance(IWidgetFactory.class)
);
domainHandler = new DomainHandler(injector, editorModel);
And the DomainHandler starts like this:
public class DomainHandler {
@Inject
private IWidgetFactory widgetFactory;
@Inject
private Injector injector;
public DomainHandler(
final Injector injector, final EditorModelItem editorModelItem
) {
System.out.printf(
"injector in domainHandler=%s\n",
injector
);
System.out.printf(
"injector2 in domainHandler=%s\n",
getInjector(null)
);
System.out.printf(
"widgetFactory in domainHandler=%s\n",
widgetFactory
);
System.out.printf(
"injector parameter=%s\n",
this.injector
);
}
@Inject
public Injector getInjector(final Injector injector) {
return injector;
}
}
And I got this:
binding WidgetFactory
widgetFactory=org.rulez.demokracia.zenta3.editor.widgets.WidgetFactory@39957a81
injector in domainHandler=Injector[bindings=[ProviderInstanceBinding[key=Key[type=com.google.inject.Injector...
injector2 in domainHandler=null
widgetFactory in domainHandler=null
injector parameter=null
DomainHandler constructor
The injector output actually contain this:
LinkedKeyBinding[key=Key[type=org.rulez.demokracia.zenta3.editor.widgets.IWidgetFactory,
annotation=[none]],
source=org.rulez.demokracia.zenta3.editor.ZentaEditorModule.configure(ZentaEditorModule.java:152),
scope=Scopes.NO_SCOPE,
target=Key[type=org.rulez.demokracia.zenta3.editor.widgets.WidgetFactory,
annotation=[none]]],
From that it seems that nothing get injected into my DomainManager instance, at none of the @Inject annotations. Interestingly there are other classes in the code which also have the injector injected, and those are working. So I guess I do something wrong at the initialization. But what?
Solution
Youre not creating your domainhandler through guice and therefore the @inject annotations do nothing. If you want to create this object both ways just use constructor injection and remove the @inject from your fields.
@inject
public DomainHandler(Injector injector, WidgetFactory widgetFactory) {
this.injector = injector;
this.widgetFactory = widgetFactory
}
This way passing them in manually or using getInstance will do the same thing.
@inject on getters doesn't make sense, it can be used on getters but even in the docs is says not normally, and your passing it a null when you print it from your constructor.
Answered By - kendavidson