How to use Guice's Injector?

2019-06-16 06:19发布

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?

And is it true that we always must use Injector#getInstance(SomeClass.class) to get classes where we putted Guice's @Inject annotations?

1条回答
甜甜的少女心
2楼-- · 2019-06-16 07:03

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.

查看更多
登录 后发表回答