I'm trying to put a enumeration into the ginjector with these lines of code:
ClientGinjector.java
MyEnum getMyEnum();
ClientModule.java
bind(MyEnum.class).in(Singleton.class);
But when I'm trying to compile I get the following error:
[ERROR] Error injecting bla.blup.MyEnum: Unable to create or inherit binding: Binding requested for constant key 'bla.blup.MyEnum' but no explicit binding was found
Can anyone please help me?
An enum class cannot be constructed, its only valid instances are its enum values. That menas you have to bind a specific enum value that will be injected into whatever field or parameter of that enum type.
Guice/GIN encourages you to use binding annotations for constants, so you can possibly inject different constant values depending on context; e.g.
@Named("foo") @Inject MyEnum myEnum;
–
bindConstant().annotatedWith(Names.named("foo")).to(MyEnum.FOO);
If you don't want to use a binding annotation (because you know you'll only ever want a single enum value throughout your app), you cannot use bindConstant()
, but you can use toInstance
:
@Inject MyEnum myEnum;
…
bind(MyEnum.class).toInstance(MyEnum.FOO);
This will only work in Guice though, not in GIN, which doesn't have toInstance
. In GIN, you have to use a Provider
class or a @Provides
method:
class MyEnumProvider implements Provider<MyEnum> {
@Override
public MyEnum get() {
return MyEnum.FOO;
}
}
…
bind(MyEnum.class).toProvider(MyEnumProvider.class);
or
@Provides
MyEnum provideMyEnum() {
return MyEnum.FOO;
}
Both approaches above will also work with Guice.