Reputation: 1212
In all of the Guice examples I have found, getting an instance involves calling Injector.getInstance()
with the concrete class as a parameter. Is there a way to get an instance from Guice using only the interface?
public interface Interface {}
public class Concrete implements Interface {}
Interface instance = injector.getInstance(Interface.class);
Thanks
Upvotes: 2
Views: 4948
Reputation: 10519
Without using a Module
, you can also specify the implementation class to be used by default, directly in the interface declaration:
@ImplementedBy(Concrete.class)
public interface Interface {}
This doesn't necessarily fit every situation but I found this comes in handy most of the times.
Additionnally, when using @ImplementedBy
annotation, you can still override the implementation class by binding another concrete class in a Module
. That can also be useful.
Upvotes: 0
Reputation: 14077
It works for interface as well:
bind( Interface.class ).to( Concrete.class );
Upvotes: 0
Reputation: 18397
Actually that's exactly what Guice is made for.
In order to make getInstance() work with an interface you'll need to first bind an implementation of that interface in your module.
So you'll need a class that looks something like this:
public class MyGuiceModule extends AbstractModule {
@Override
protected void configure() {
bind(Interface.class).to(Concrete.class);
}
}
Then when you create your injector you just need to pass an instance of your module in:
Injector injector = Guice.createInjector(new MyGuiceModule());
Now your call to injector.getInstance(Interface.class)
should return a new instance of Concrete using the default constructor.
Of course there are many many more ways you can do bindings but this is probably the most straight forward.
Upvotes: 10