Question

I'm trying to use Google Guice with the @Inject and @Singleton properties as follows:

I have:

  1. A Module with an empty configure() method.
  2. An interface IFoo
  3. A class Foo (implementing IFoo), annotated with @Singleton, with a parameter-less constructor annotated with @Inject. This is the single annotated constructor.

The classes, constructor and interface are public, and still I'm getting the following error:

No implementation for IFoo was bound.

Was it helpful?

Solution

You mean you get the error when doing this?

IFoo foo = injector.getInstance(IFoo.class);

Well then it is obvious. If the configure() is empty how should guice know with what class to satisfy the dependency for IFoo.

Just add this in the configure() method and it should work. Now guice knows with what class to satisfy the dependency.

bind(IFoo.class).to(Foo.class);

If you don't want to configure this in the module you can annotate the interface. e.g.

@ImplementedBy(Foo.class)
public interface IFoo {
  ...
}

The @Singleton annotations only tells guice to return the same instance for the class (the Singleton Pattern) everytime a request for the class is made via Injector.getInstance() instead of creating a new instance everytime. But note that this is only a Singleton per Injector rather then per Classloader.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top