java – Injector. getInstance(..) Returns a new instance of the singleton
•
Java
My module:
bind( Translator.class ).to( TranslatorImpl.class ).in( Scopes.SINGLETON );
Now I hope to get the same instance every time
Injector injector = ...; injector.getInstance( Translator.class );
But if I do
injector.getInstance( TranslatorImpl.class );
I get a new instance every time Is this a mistake or an expected behavior?
Solution
This is the expected behavior because translatorimpl Class is not bound to the singleton scope, only translator class.
If you want two getinstances (..) If both return the same instance, you can 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));
For more information, see https://github.com/google/guice/wiki/Scopes#applying -scopes.
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码