Building out the Multibindings extension, David P. Baker has written a new class that simplifies Map binding. MapBinder
uses an API that's consistent with Multibinder
:
public class SnacksModule extends AbstractModule {
protected void configure() {
MapBinder<String, Snack> mapBinder
= MapBinder.newMapBinder(binder(), String.class, Snack.class);
mapBinder.addBinding("twix").toInstance(new Twix());
mapBinder.addBinding("snickers").toProvider(SnickersProvider.class);
mapBinder.addBinding("skittles").to(Skittles.class);
}
}
Like Multibinder...
Keys must be non-null and unique. Values must be non-null. Values get resolved at injection-time, so they can be scoped. Bindings from different modules will be aggregated, which makes it usable for an application registry.
Unlike Multibinder...
For the example above, an extra binding is made for Map<String, Provider<Snack>>
. This makes it so that if values are expensive to provide, you can get just the ones you need.
This API is available in Guice svn right now. The API is subject to change before version 2. I suspect we'll probably rename Multibinder
to either SetBinder
or MultiBinder
. Any preferences?