Injector.getInstance (..) returns a new instance for singleton

My module:

bind( Translator.class ).to( TranslatorImpl.class ).in( Scopes.SINGLETON ); 

Now I expect to get the same instance every time I do

 Injector injector = ...; injector.getInstance( Translator.class ); 

But if I do

 injector.getInstance( TranslatorImpl.class ); 

I get a new instance every time. Is this a bug or an expected behavior?

+6
java dependency-injection guice
source share
1 answer

This is the expected behavior because TranslatorImpl.class not bound to a singleton scope, only Translator.class .

If you want both getInstance(..) return the same instance, you could bind the implementation to a singleton scope:

 bind(Translator.class).to(TranslatorImpl.class); bind(TranslatorImpl.class).in(Scopes.SINGLETON); assertEquals(injector.getInstance(Translator.class), injector.getInstance(TranslatorImpl.class)); 

See https://github.com/google/guice/wiki/Scopes#applying-scopes for more details.

+15
source share

All Articles