简体   繁体   中英

How to retrieve the Set of Multibound implementations of a given interface with Guice

My application is built with Guice. The application module uses a Multibinder to bind several implementations of an interface.

Multibinder<FooInterface> newSetBinder = Multibinder.newSetBinder(binder(), FooInterface.class);
newSetBinder.addBinding().to(FooInterfaceImpl.class);
newSetBinder.addBinding().to(BarInterfaceImpl.class);

The test class for this application module is responsible for ensuring that the appropriate implementations are bound. For non-Multibound bindings, this is trivial using Injector.getInstance(Class<T> type) :

assertThat("Incorrect implementation bound", injector.getInstance(SomeInterface.class), instanceOf(SomeInterfaceImpl.class));

However, this doesn't work for Multibound interfaces. I want to return a Collection of bindings for the given interface, and assert that the Collection contains the expected classes.

Is there a way to do this?

Found the answer, using:

Injector.findBindingsByType(TypeLiteral<T> type)

This method Returns all explicit bindings for {@code type}.

I can therefore use the following in my test class:

injector.findBindingsByType(new TypeLiteral<FooInterface>() {}))

..and on the returned List<Binding<FooInterface>> , I can assert that the expected class is the target of one of the bindings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM