pass1 pass1 - 4 months ago 27x
Java Question

Guice - Default binding definition

Is there a way to declare default binding in Guice 3.0 ?

Here is an example of what I expected :

//Constructor for Class Impl1
public Impl1 (@One IMyOwn own)

//Constructor for Class Impl2
public Impl2 (@Two IMyOwn own)

//Declare a default binding

//Then, if I want to bind a custom implementation for @Two

Actually, this example can't works because I must declare a binding for all annotation (@One, @Two).

Are there solutions to do that with Guice ?


Guice tries to check as much of your configuration (aka. Binding) as possible. This also means, that Guice cannot tell whether a missing binding for @One is an error or should map to some default case.

If you are interested in the details, lookup the BindingResolution sequence in Guice. Since step 4 and step 6 deal with binding annotation and step 6 explicitly forbids default, I think you are out of luck.

.6. If the dependency has a binding annotation, give up. Guice will not create default bindings for annotated dependencies.

So the best you can do is to provide Guice with a hint, that @One should map to the default like this:


So you do not need to state the concrete default class DefaultMyOwn multiple times.