Domanda

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?

È stato utile?

Soluzione 2

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.

Altri suggerimenti

A constant (primitive type, String, Class or an enum) must be explicitly bound (using bindConstant() or bind()) in your GinModule (because there's no sensible default value that GIN would inject).

That's what GIN is telling you.

The file is where the binding is requested (i.e. where the dependency is declared) that GIN cannot honor.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top