假设我有一个接口Foo。它由具体实现CompositeFoo、FooA、FooB和FooC实现。此外,CompositeFoo如下:
public class CompositeFoo implements Foo {
@Inject public CompositeFoo(List<? extends Foo> elements);
}在Guice PrivateModule中,我希望将Foo绑定到CompositeFoo,列表是一个FooA,后面跟着一个FooB或FooC。(这必须是一个列表,因为顺序很重要;这排除了多绑定作为解决方案的可能性。)
问题是,我看到了一些循环。假设CompositeFoo的提供者如下所示:
public class CompositeFooProvider implements Provider<Foo> {
@Inject private FooA first;
@Inject @Named("Inner") private Foo second;
@Override public Foo get() { return new CompositeFoo(asList(first, second)); }
}提供第二个Foo ( FooB或FooC)的模块如下:
public class InnerModule extends PrivateModule {
private final Key<? super Foo> bindingKey; // key will be exposed, bound to the Foo below
// configure() deals with deps of FooB and FooC
@Provides
public Foo getInnerFoo(...) {
// Assume that the args are such that if they are "valid", we should return a FooB, else FooC
if (...) return new FooB(...);
else return new FooC(...);
}
}当我试图构造外部模块时,就会出现循环性:我需要安装InnerModule (传入Key.get(Foo.class, Names.named("Inner"))作为绑定键),以获得第二个Foo,但是Foo已经绑定在外部模块中,因为它绑定到CompositeFooProvider。如何解决这种循环性?将@Provides方法转换为自己的Provider是否足够?
发布于 2014-11-15 22:41:37
@Provides Foo方法为Foo提供了一个绑定,该绑定与外部模块中的Foo绑定冲突。因此,将它绑定为其他东西:
public class InnerModule extends PrivateModule {
private final Key<Foo> bindingKey; // key will be exposed, bound to the @Inner Foo below
@BindingAnnotation
@Target({ FIELD, PARAMETER, METHOD })
@Retention(RUNTIME)
@interface Inner {
}
@Override
protected void configure() {
bind(bindingKey).to(Key.get(Foo.class, Inner.class));
expose(bindingKey);
}
@Provides
@Inner Foo getInnerFoo(...) {
// Assume that the args are such that if they are "valid", we should return a FooB, else FooC
if (...) return new FooB(...);
else return new FooC(...);
}
}或者你可以
@Provides
@Exposed
@Named("Inner") Foo getInnerFoo(...) {
// Assume that the args are such that if they are "valid", we should return a FooB, else FooC
if (...) return new FooB(...);
else return new FooC(...);
}直接而不麻烦地传递绑定密钥。
https://stackoverflow.com/questions/26939304
复制相似问题