java - Guice AssistedInject 不会注入(inject)工厂

标签 java nullpointerexception guice factory assisted-inject

我正在尝试使用 Guice 3.0 AssistedInject,它不会实例化工厂。

SSCCE代码:

父类

public class ParentClass() {
  @Inject private MyFactory myFactory;
  private final Foo foo;
  private final Bar bar;
  public ParentClass() {
    if(myFactory == null) System.err.println("Error: I should have injected by now!");
    foo = myFactory.create(new Map<String, Object>());
    // etc.
  }
}

工厂接口(interface)

public interface MyFactory {
  Foo create(Map<String, Object> mapA);
  Bar create(Map<String, Object> mapB, Map<String, Object> mapC);
}

模块

public class ParentModule extends AbstractModule {
  @Override
  protected void configure() {
    install(new FactoryModuleBuilder()
        .implement(Foo.class, FooImpl.class)
        .implement(Bar.class, BarImpl.class)
        .build(MyFactory.class));
  }

FooImpl

public class FooImpl implements Foo {
  private final Map<String, Object> mapA;
  @AssistedInject
  public FooImpl(@Assisted Map<String, Object> mapA) {
    this.mapA = mapA;
  }
}

BarImplFooImpl 非常相似。这里出了什么问题?另请注意,我在这里尝试了 @AssistedInject@Inject,两者都会导致错误。

输出:

Error: I should have injected by now!
Exception in thread "main" com.google.inject.ProvisionException: Guice provision errors:

1) Error injecting constructor, java.lang.NullPointerException
  at ParentClass.<init>(ParentClass.java:7)
  while locating com.my.package.ParentClass

1 error
        at com.google.inject.internal.InjectorImpl$4.get(InjectorImpl.java:987)
        at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1013)
        at com.my.package.ParentMain.main(ParentMain.java:16)
Caused by: java.lang.NullPointerException
        at com.my.package.ParentClass.<init>(ParentClass.java:9)
        at com.my.package.ParentClass$$FastClassByGuice$$d4b3063a.newInstance(<generated>)
        at com.google.inject.internal.cglib.reflect.$FastConstructor.newInstance(FastConstructor.java:40)
        ... 8 more

请注意第 9 行是第一次调用 myFactory.create()

最佳答案

根据 Guice 的 javadoc ,字段注入(inject)构造函数注入(inject)之后执行。

我假设您的 ParentClass 实例是由 Guice 创建的。当您的 ParentClass 的构造函数被执行时,它的 myFactory 字段还没有被注入(inject)。

关于java - Guice AssistedInject 不会注入(inject)工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14760219/

相关文章:

java - 什么是NullPointerException,我该如何解决?

java - Errai Jax-RS 不发射

java - Vertx 不获取外部 conf 文件

java - 为什么 guice 不注入(inject)之前实例化的 @SessionScoped 对象?

java - 为什么我的聊天应用程序无法在路由器后面运行?

java - 方法 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)

java - 如何将资源 ID 作为参数传递;没有空指针异常

hadoop 空指针异常

java - 我的 onResume 取决于 `onViewCreated` 。我怎样才能重新设计它?

用于 Android 的基于 Java 的加密库