Guice范围和AssistedInject

时间:2018-03-26 13:30:34

标签: java guice assisted-inject

我有使用AssistedInject创建我的类工厂的代码。现在我要做的是创建一些对象,每个对象都注入一个不同的集合项(反向多边形可以说)。

我的方法是使用包含Iterator的自定义Scope来提供Items,但我做错了:

IterationScope.java:

public class IterationScope implements Scope {

  private Iterator<?> iterator;

  public IterationScope() {
  }

  /**
   * provide scoped Items
   * @param key - the key for the requested item
   * @param unscoped - the unscoped provider
   * @param <T> - the type of the requested object
   * @return - the requested provider
   */
  @SuppressWarnings("unchecked")
  @Override
  public <T> Provider<T> scope(Key<T> key, Provider<T> unscoped) {
    return Providers.<T>of((T)iterator.next());
  }

  public void enterScope(Iterator<?> iterator) {
    this.iterator = iterator;
  }

}

IterationScoped.java:

@Target({ FIELD, PARAMETER })
@Retention(RUNTIME)
@ScopeAnnotation @BindingAnnotation
public @interface IterationScoped {
}

在模块中:

IterationScope itScope = new IterationScope();
bindScope(IterationScoped.class, itScope);
bind(IterationScope.class).toInstance(itScope);
bind(ImplementationDataType.class).annotatedWith(IterationScoped.class).toProvider(Providers.of(null)).in(itScope);
/* do AssistedInject stuff */

我试着得到这样的价值:

@Inject @IterationScoped ImplementationDataTypedataType

并设置范围如下:

@Inject private IterationScope iterationScope; 

[...]
iterationScope.enterScope(someCollection.iterator);
for (ImplementationDataType message: someCollection){   
generatorChain.addNextFileGenerator(generatorFactory.create(param1,false));
}

我遇到的问题是,在创建工厂时,我在IteratorScope.scope中得到NullPointerException,因为没有设置Iterator。

java.lang.NullPointerException
    at com.conti.xcit.utilities.guice.IterationScope.scope(IterationScope.java:45)
    at com.google.inject.internal.Scoping.scope(Scoping.java:240)
    at com.google.inject.internal.BindingProcessor$1.visit(BindingProcessor.java:104)
    at com.google.inject.internal.BindingProcessor$1.visit(BindingProcessor.java:68)
    at com.google.inject.internal.ProviderInstanceBindingImpl.acceptTargetVisitor(ProviderInstanceBindingImpl.java:62)
    at com.google.inject.internal.BindingProcessor.visit(BindingProcessor.java:68)
    at com.google.inject.internal.BindingProcessor.visit(BindingProcessor.java:42)
    at com.google.inject.internal.BindingImpl.acceptVisitor(BindingImpl.java:93)
    at com.google.inject.internal.AbstractProcessor.process(AbstractProcessor.java:55)
    at com.google.inject.internal.InjectorShell$Builder.build(InjectorShell.java:177)
    at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:103)
    at com.google.inject.internal.InjectorImpl.createChildInjector(InjectorImpl.java:217)
    at com.google.inject.internal.InjectorImpl.createChildInjector(InjectorImpl.java:224)
    at [... where I inject the Factory ... ]

我的期望是工厂只在我实际请求对象时才尝试找到范围提供者,而不是在创建工厂时。有没有办法解决这个问题?我有一个丑陋的想法,涉及带有递增计数器的作用域提供程序,以便选择集合中的正确项目,但我想要一个更清洁的方法。

0 个答案:

没有答案