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?
Using GuiceIn each of your constructors that need to have something injected in them, you just add an @Inject annotation and that tells Guice to do it's thing. Guice figures out how to give you an Emailer based on the type. If it's a simple object, it'll instantiate it and pass it in.
The implementation is very easy to understand. We need to create Injector object using Guice class createInjector() method where we pass our injector class implementation object. Then we use injector to initialize our consumer class. If we run above class, it will produce following output.
Note that the only Guice-specific code in the above is the @Inject annotation. This annotation marks an injection point. Guice will attempt to reconcile the dependencies implied by the annotated constructor, method, or field.
Annotation Type Inject. @Target(value={METHOD,CONSTRUCTOR,FIELD}) @Retention(value=RUNTIME) @Documented public @interface Inject. Annotates members of your implementation class (constructors, methods and fields) into which the Injector should inject values.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With