如何使用Guice的喷油器? [英] How to use Guice's Injector?
问题描述
我正在学习Guice,但我不清楚如何使用Injector
实例.最好在应用程序引导程序上创建一次Injector
实例,并将其设为公共单例?
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?
难道我们总是必须使用Injector#getInstance(SomeClass.class)
来获取将Guice的@Inject
注释放入其中的类吗?
And is it true that we always must use Injector#getInstance(SomeClass.class)
to get classes where we putted Guice's @Inject
annotations?
推荐答案
您不应将注入器作为全局单例传递.您是否看过: https://github.com/google/guice/wiki/GettingStarted?请注意,RealBillingService
不会使用注入器来获取CreditCardProcessor
和TransactionLog
的实例.相反,Guice在创建实例时会为您处理所有这一切.
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.
If you're in a situation where you need Guice to create many objects of the same type consider using a Provider and injecting that provider.
这篇关于如何使用Guice的喷油器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!