Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Guice's 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?

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

like image 295
WelcomeTo Avatar asked Feb 12 '13 19:02

WelcomeTo


People also ask

How does Guice injector work?

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.

How do you inject a Guice class?

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.

What does @inject mean Guice?

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.

What is @inject annotation in Guice?

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.


1 Answers

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.

like image 63
condit Avatar answered Oct 28 '22 01:10

condit