java 如何使用Guice的注射器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14839956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use Guice's Injector?
提问by MyTitle
I'm in process of learning Guice and I don't clearly understand how to use Injector
instance. It's better to create Injector
instance once on application bootstrap, and make it public singleton?
我正在学习 Guice,我不清楚如何使用Injector
实例。最好Injector
在应用程序引导程序上创建一次实例,并将其设为公共单例?
And is it true that we always must use Injector#getInstance(SomeClass.class)
to get classes where we putted Guice's @Inject
annotations?
我们是否总是必须使用Injector#getInstance(SomeClass.class)
来获取放置 Guice@Inject
注释的类?
采纳答案by condit
You should not pass the injector around as a global singleton. Have you looked at: https://github.com/google/guice/wiki/GettingStarted? Note that RealBillingService
does not use the injector to get instances of CreditCardProcessor
and TransactionLog
. Instead Guice handles all this for you when creating the instance.
您不应该将注入器作为全局单例传递。你有没有看过:https: //github.com/google/guice/wiki/GettingStarted?请注意,RealBillingService
不使用注入器来获取CreditCardProcessor
和 的实例TransactionLog
。相反,Guice 在创建实例时会为您处理所有这些。
If you're in a situation where you need Guice to create many objects of the same type consider using a Providerand injecting that provider.
如果您需要 Guice 创建许多相同类型的对象,请考虑使用Provider并注入该提供程序。