Atom Feed SITE FEED   ADD TO GOOGLE READER

Guice Multibindings extension checked in!

As previously alluded to, I've started work on the Multibindings API. I've checked in the initial implementation, and I'm pretty excited about it. You can grab it from svn.

This feature is ideal for lightweight plugin-type architectures, where you've got multiple modules each contributing Servlets, Actions, Filters, Components or even just names.

The Multibinder Javadoc:

An API to bind multiple values separately, only to later inject them as a complete collection. Multibinder is intended for use in your application's module:
public class SnacksModule extends AbstractModule {
protected void configure() {
Multibinder<Snack> multibinder
= Multibinder.newSetBinder(binder(), Snack.class);
multibinder.addBinding().toInstance(new Twix());
multibinder.addBinding().toProvider(SnickersProvider.class);
multibinder.addBinding().to(Skittles.class);
}
}

With this binding, a Set<Snack> can now be injected:
class SnackMachine {
@Inject
public SnackMachine(Set<Snack> snacks) { ... }
}

Create multibindings from different modules is supported. For example, it is okay to have both CandyModule and ChipsModule to both create their own Multibinder<Snack>, and to each contribute bindings to the set of snacks. When that set is injected, it will contain elements from both modules.

Elements are resolved at set injection time. If an element is bound to a provider, that provider's get method will be called each time the set is injected (unless the binding is also scoped).

Annotations are be used to create different sets of the same element type. Each distinct annotation gets its own independent collection of elements.

Elements must be distinct. If multiple bound elements have the same value, set injection will fail.

Elements must be non-null. If any set element is null, set injection will fail.
Hi

I recently tried the new api. Looks great.

What was a bit confusing for me is that there was no way to bind "Lists" or to bind Arrays.

This is a bit confusing but I think you explained why in another posting.
Georgo - I blogged why there's no bindings to Lists or arrays.
The others are pretty self explanatory, but what's:

multibinder.addBinding().to(Skittles.class);

Do exactly? I assume it'll instantiate a single Skittle at injection-time? Could you tell it to build 5? Sort of as a way to inject a default set of something into an object that then modifies them?

multibinder.addBinding().to(Skittles.class).createCount(5);

Or similar?
It would have been nice if they had implemented the stringBinder.addBinding().annotatedWith
as well.