views:

423

answers:

1

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.

+2  A: 

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.

jitter
Doesn't the @Singleton annotation on Bar tell Guiced that it is the concrete implementation of IBar?I don't like to have a large Module() - I prefer to annotate classes. How does one accomplish that with Guist?
ripper234
Answer extended
jitter
Thanks, that's what I needed.
ripper234