-
Notifications
You must be signed in to change notification settings - Fork 1.7k
TOO_MANY_CONSTRUCTORS
Guice will throw a TOO_MANY_CONSTRUCTORS
error when there are more than one
@Inject
annotated constructors in a class that uses
constructor injection.
When multiple constructors are annotated with @Inject
, Guice does not know
which one to use.
This usually happens when a new constructor is added to the class that already
has a constructor annotated with @Inject
. Since @Inject
by itself does not
have any effect unless Guice is used to construct those objects, this mistake
may only become clearer later when the class is integrated with Guice.
Example class that has too many injectable constructors:
final class Foo {
@Inject
Foo(Bar bar) {
...
}
@Inject
Foo(Bar bar, Optional<Baz> baz) {
...
}
}
There are two ways to fix this error:
-
Simply remove
@Inject
from all but one constructor:final class Foo { Foo(Bar bar) { ... } @Inject // Guice will use this constructor. Foo(Bar bar, Optional<Baz> baz) { ... } }
-
Remove all the
@Inject
annotations from those constructors and add an explicit binding for the class. The recommended way to do this is to add a@Provides
method for the class:final class Foo { Foo(Bar bar) { ... } Foo(Bar bar, Optional<Baz> baz) { ... } } final class FooModule extends AbstractModule { @Provides Foo provideFoo(Bar bar) { return new Foo(bar); // Calls the one argument constructor explicitly. } }
In rare cases that you can't use
@Provides
method because you need to use Guice with AOP features, you can use constructor binding to tell Guice explicitly which constructor to use.
-
User's Guide
-
Integration
-
Extensions
-
Internals
-
Releases
-
Community