Guice AssistedInject不会注入工厂 [英] Guice AssistedInject won't inject the factory

查看:455
本文介绍了Guice AssistedInject不会注入工厂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to use Guice 3.0 AssistedInject, and it won't instantiate the factory.

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



工厂界面



Factory Interface

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



模块



Module

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



FooImpl

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

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

BarImpl is very similar to FooImpl. What is going wrong here? Note also that I tried both @AssistedInject and @Inject here, both cause the error.

输出:

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.creat的行e()

Note that line 9 is the line of the first call to myFactory.create()

推荐答案

根据Guice的 javadoc ,在 构造函数注入后 执行字段注入。

According to Guice's javadoc, field injection is performed after constructor injection.

我假设你的 ParentClass 实例是由Guice创建的。执行 ParentClass 的构造函数时,其 myFactory 字段尚未注入。

I assume your ParentClass instance is created by Guice. When your ParentClass's constructor is executed, its myFactory field has not been injected yet.

这篇关于Guice AssistedInject不会注入工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆