Guice equivalent of Spring's @Autowire list of instances

a 夏天 提交于 2019-12-21 12:19:56

问题


In spring when I do:

@Autowire
List<MyInterface> myInterfaces;

then this list will get populated by all beans which implement MyInterface. I didn't have to create bean of type List<MyInterface>.

I'm looking for such behaviour in Google Guice.

Sofar I went with:

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

Now if I have a bean which implements MyInterface and I bind it, say via:

bind(MyInterfaceImpl.class).asEagerSingleton();

it won't be included in my multibinder. I need to add:

myInterfaceBinder.addBinding.to(MyInterfaceImpl.class);

This is somewhat more complicated than what Spring offers. So I was wonmdering whether I'm not using it in wrong way. So is there easier way of achieving this?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/25506133/guice-equivalent-of-springs-autowire-list-of-instances

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