My Module:
bind( Translator.class ).to( TranslatorImpl.class ).in( Scopes.SINGLETON );
Now I expect to get the same instance everytime when I do
Injector injector = ...;
injector.getInstance( Translator.class );
But if I do
injector.getInstance( TranslatorImpl.class );
I get a new instance everytime. Is this a bug or expected behaviour ?
This is the expected behaviour because TranslatorImpl.class
isn't bound to the singleton scope, only Translator.class
is.
If you want both getInstance(..)
to return the same instance, you could bind the implementation to the 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.