有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用TypeLiteral的guice Java注入实现

我有一个提供接口的项目,我们称之为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如何处理实例化。由于制作人必须依赖于我的项目,我想它在最后实例化是有道理的,从而导致了我最初的问题


共 (1) 个答案

  1. # 1 楼答案

    您正在寻找多重绑定->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)
    

    I would suggest you to have a look at MapBindings which allows you provide keys for each implementation and then you will be able to inject your bindings as a Map