How to Override a Binding in a Child Module: "was already configured"

12,710 views
Skip to first unread message

Jeremy Chone

unread,
Sep 30, 2009, 1:45:19 PM9/30/09
to google-guice
Hi,

I am trying to override a binding for a Child Injector Module, but I
get the following error:

"A binding to XXX was already configured at YYY"

I guess, I am doing something wrong.

But basically, I have a parent Guice Module and then create one or
more "childInjector," each based on a different Mobules. In the parent
Guice Module, I have one binding for XXX, but want to allow the
developer to override this binding for a particular submodule?

Should I use PrivateModule for this? Or am I missing something
obvious?



Jeremy,

Jeremy Chone

unread,
Sep 30, 2009, 1:56:27 PM9/30/09
to google-guice
Sorry, I found that: http://publicobject.com/2008/05/overriding-bindings-in-guice.html

This should answer my question.

Jeremy Chone

unread,
Sep 30, 2009, 2:01:49 PM9/30/09
to google-guice
Actually, the three solutions for overriding the bindings do not
really fit my need.

I would like a way to override a binding for a specific child injector
(or private Module).

Jeremy,

limpb...@gmail.com

unread,
Oct 1, 2009, 1:57:36 AM10/1/09
to google-guice
So you can't override a binding from a parent injector in its child.
From the createChildInjector() javadoc:
No key may be bound by both an injector and one of its ancestors.
This includes just-in-time bindings. The lone exception is the key for
Injector.class, which is bound by each injector to itself.

Alternatives to consider:
- using a qualifier like @Named for the two different types
- remove the binding from the parent injector. You could move it to a
2nd private module. Sibling modules are permitted to repeat bindings.

Cheers,
Jesse

Jeremy Chone

unread,
Oct 6, 2009, 3:56:52 AM10/6/09
to google-guice
Thanks, I removed the binding from the parent inspector.

Now, I need to find out if I can override a binding in a subclass (in
the configure methods).

Etienne Neveu

unread,
Oct 6, 2009, 6:37:19 AM10/6/09
to google-guice
You can do this by extracting the parts you want to override in a
protected method, and then override it in the subclassed module.

Or you could consider using com.google.inject.util.Modules.override
(Module...)

There was a nice post on this subject here
http://publicobject.com/2008/05/overriding-bindings-in-guice.html
(By the way, this blog has a lot of other cool posts about Guice (as
well as Google Collections) )

Regards,

Etienne
Reply all
Reply to author
Forward
0 new messages