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

Pavel picture Pavel · Jan 25, 2011 · Viewed 14.7k times · Source

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?

Answer

Olivier Grégoire picture Olivier Grégoire · Jan 25, 2011

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.