我有一个项目,它提供了一个接口,我们称它为IImplementMe,我想将它注入到我的项目中。这个接口将由不同的生产者实现,所以我需要注入所有实现。我正在尝试使用TypeLiteral来实现这一点。
下面是生产者的代码:
@Singleton
public class SomeImplementation implements IImplementMe {
private final String value;
@Inject
public SomeImplementation(final SomeOtherConfig configuration) {
this.value= configuration.getValue();
}
@Override
public String getValue() {
return value;
}
}在我的注册表类中有register(IImplementMe.class).to(SomeImplementation.class);
然后,在我的项目中,我像这样注入它:
@Inject
public SomeEndpoint(final List<IImplementMe> implementations){
///
}我把它绑定成
private static class MarketDataSetTypeLiteral extends TypeLiteral<List<IImplementMe>> {
}
bind(new MarketDataSetTypeLiteral()).toRegistry();我确保调用了我的SomeIMplementation构造函数,但是在我的端点中,列表是空的,所以没有提供任何实现。我正在使用guice进行注射。有什么想法吗?
LE:事实证明,所提供的实现是在创建我的端点类之后创建的(在创建时它注入了一个空列表的引用)。在生命周期的后期,引用会随着实现的更新而更新,所以在guice完成它的工作之后,我实际上可以访问它。
我猜这是由于maven依赖,以及guice处理实例化的方式。由于生产者必须依赖于我的项目,我猜它最后被实例化是有意义的,因此导致了我最初的问题。
发布于 2016-04-19 16:23:19
您正在寻找多绑定-> https://github.com/google/guice/wiki/Multibindings
public class IImplementMeModule extends AbstractModule {
public void configure() {
Multibinder< IImplementMe > uriBinder = Multibinder.newSetBinder(binder(), IImplementMe.class);
uriBinder.addBinding().to(SomeImplementationOfIImplementMe.class);
uriBinder.addBinding().to(AnotherImplementationOfIImplementMe.class);
... // bind plugin dependencies, such as our Flickr API key
}
}然后,您可以按如下方式注入这组IImplemetnMe
@Inject TweetPrettifier(Set<IImplemetnMe> implementations)我建议您看一看MapBindings,它允许您为每个实现提供密钥,然后您将能够将绑定作为映射
注入
https://stackoverflow.com/questions/36690178
复制相似问题