无法在javafx项目中注入依赖项

时间:2019-04-15 13:06:49

标签: javafx dependency-injection guice

我正在尝试在javaFX项目中进行依赖项注入。

我有一个

@Singleton
public class WidgetFactory implements IWidgetFactory

我的public class ZentaEditorModule extends MvcFxModule包含

  @Override
  protected void configure() {
    super.configure();
    //some other code
    System.out.println("binding WidgetFactory");
    bind(IWidgetFactory.class).to(WidgetFactory.class);
  }

在我的public class ZentaApplication extends Application中,它具有以下功能,可以在应用程序初始化中运行:

final Injector injector = Guice.createInjector(module);
System.out.printf(
    "widgetFactory=%s\n", injector.getInstance(IWidgetFactory.class)
);
domainHandler = new DomainHandler(injector, editorModel);

DomainHandler像这样开始:

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;
  }
}

我明白了:

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

喷油器输出实际上包含以下内容:

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]]],

由此看来,@ Inject批注中没有任何内容注入我的DomainManager实例中。有趣的是,代码中还有其他类别,这些类别也注入了喷射器,并且它们正在工作。 所以我想我在初始化时做错了。但是呢?

1 个答案:

答案 0 :(得分:2)

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.