Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guice equivalent of Spring's @Autowire list of instances

Tags:

java

guice

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?

like image 487
Jan Zyka Avatar asked Aug 26 '14 12:08

Jan Zyka


2 Answers

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.

like image 121
Stefan Walter Avatar answered Oct 19 '22 12:10

Stefan Walter


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.

like image 1
maaartinus Avatar answered Oct 19 '22 13:10

maaartinus