How to use Guice's Injector?

MyTitle picture MyTitle · Feb 12, 2013 · Viewed 17.2k times · Source

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?

Answer

condit picture condit · Feb 12, 2013

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.