Java – What is MembersInjectors in Guice?

What is MembersInjectors in Guice?… here is a solution to the problem.

What is MembersInjectors in Guice?

This can be seen in the official document .

When binding to providers or writing extensions, you may want Guice to inject dependencies into an object that you construct yourself. To do this, add a dependency on a MembersInjector (where T is your object’s type), and then call membersInjector.injectMembers(myNewObject).

I don’t understand the full picture of how to use MembersInjector.
When you want Guice to inject some instances into the object you want to create, it’s best to only bind appropriately. So, when to use this MemebersInjector?
Even if you want to use a provider like bind().toProvider(), why don’t we need to use MembersInjector?

Can anyone explain?

Solution

The key word here is “you build yourself”.

For bind(A.class).to(B.class), Guice creates the B instance itself and injects it, methods, and fields based on its @Inject. However, in some cases, you might need to get an instance from somewhere other than Guice. This may be in cases where the constructor may not easily accept extra arguments, such as Eclipse SWT or Java serialization Google GSON , Apache Crunch, or any other case where instances are created out of your control.

In those cases, instead of getInstance(YourClass.class) or getProvider(YourClass.class), you want Guice to perform all the injections it can perform on the instance you already have. This is MembersInjector Where to come in: You can inject a MembersInjector<YourClass> whichever you need it or you can use it Injector.getMembersInjector Create any MembersInjector based on Class or TypeLiteral.

Related Problems and Solutions