Kazuya Tomita
Kazuya Tomita

Reputation: 697

What is the MembersInjectors in Guice?

In the official document, you can see this sentence.

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 whole picture of how to use MembersInjector. When you want Guice to inject some instances into an object that you want to create, it is good to just make appropriate bindings. So, when do you use this MemebersInjector? Even when you want to use providers like bind().toProvider(), why don't we need to use MembersInjector?

Could anyone explain?

Upvotes: 3

Views: 1384

Answers (1)

Jeff Bowman
Jeff Bowman

Reputation: 95704

The key words here are "that you construct yourself".

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

In those cases, rather than getInstance(YourClass.class) or getProvider(YourClass.class), you want Guice to perform all the injection it can on an instance you already have. This is where MembersInjector comes in: You can inject a MembersInjector<YourClass> wherever you need it, or you can use Injector.getMembersInjector to create an arbitrary MembersInjector based on a Class or TypeLiteral.

Upvotes: 3

Related Questions