Guice equivalent of Spring's @Autowire list of instances

感情迁移 提交于 2019-12-04 04:22:36

I haven't used it that way myself, yet, but according to Guice's API documentation, I think you should be able to write something not much more than this once:

bindListener(Matchers.subclassesOf(MyInterface.class), new TypeListener() {
  public <I> void hear(TypeLiteral<I> typeLiteral,
                       TypeEncounter<I> typeEncounter) {
    myInterfaceBinder.addBinding().to(typeLiteral);
  }
}

Then, when you bind an implementation via

bind(MyInterfaceImpl.class).asEagerSingleton();

it should be added to your multibinder automatically.

A hacky solution would be to do it all in a loop:

Multibinder<MyInterface> myInterfaceBinder
    = MultiBinder.newSetBinder(binder(), MyInterface.class);

Class<? extends MyInterface>[] classes = {
    MyInterfaceImpl,
    YourInterfaceImpl.class,
    MyCatsInterfaceImpl
};

for (Class<? extends MyInterface> c : classes) {
    bind(c).asEagerSingleton();
    myInterfaceBinder.addBinding.to(c);
}

It's hacky, it's applicable for such simple cases only, but it's simple and DRY.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!