Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind one implementation to a few interfaces with Google Guice?

I need to bind one class as implementation of two interfaces. And it should be binded in a singleton scope.

What I've done:

bind(FirstSettings.class).     to(DefaultSettings.class).     in(Singleton.class); bind(SecondSettings.class).     to(DefaultSettings.class).     in(Singleton.class); 

But, obviously, it leads to creation of two different instances, because they are binded to the different keys.

My question is how can I do that?

like image 207
Pavel Avatar asked Jan 25 '11 09:01

Pavel


People also ask

Can two interfaces be implemented?

However, it can be achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple interfaces, separate them with a comma (see example below).

What does @inject do Guice?

Note that the only Guice-specific code in the above is the @Inject annotation. This annotation marks an injection point. Guice will attempt to reconcile the dependencies implied by the annotated constructor, method, or field.

How does Guice binding work?

Guice figures out how to give you an Emailer based on the type. If it's a simple object, it'll instantiate it and pass it in. If it has dependencies, it will resolve those dependencies, pass them into it's constructor, then pass the resulting object into your object.

What are Guice bindings?

Overview of bindings in Guice. A binding is an object that corresponds to an entry in the Guice map. You add new entries into the Guice map by creating bindings.


1 Answers

Guice's wiki has a documentation about this use case.

Basically, this is what you should do:

// Declare that the provider of DefaultSettings is a singleton bind(DefaultSettings.class).in(Singleton.class);  // Bind the providers of the interfaces FirstSettings and SecondSettings // to the provider of DefaultSettings (which is a singleton as defined above) bind(FirstSettings.class).to(DefaultSettings.class); bind(SecondSettings.class).to(DefaultSettings.class); 

There is no need to specify any additional classes: just think in terms of Providers and the answer comes rather naturally.

like image 51
Olivier Grégoire Avatar answered Oct 05 '22 15:10

Olivier Grégoire