Injecting values into a bean provided by @Provides

41 views
Skip to first unread message

zonski

unread,
Dec 10, 2011, 7:38:40 PM12/10/11
to google-guice
If I bind my bean using either of the following:

bind(MyInterface.class).to(MyInterfaceImpl.class);

or

bind(MyInterface.class).toInstance(new MyInterfaceImpl());

The resulting bean will have all it's fields marked with @Inject
automatically injected, just as I'd expect.

However if I use an @Provides marked method to do exactly the same
thing then my fields are not injected:

// resulting bean is not injected?
@Provides public MyInterface myInterface() {
return new MyInterfaceImpl();
}

This seems a bit odd for me. I'm guessing this is done to allow
developers to control the wiring for their provided classes, but in my
case I don't want to control this, I just want to control how the bean
gets instantiated (because in my real scenario I actually have to load
my bean from an XML file) and have Guice still do all the autowiring.

Is this really not possible?

Willi Schönborn

unread,
Dec 10, 2011, 7:43:00 PM12/10/11
to google...@googlegroups.com

You could inject the Injector into your method and call Injector.injectMembers(bean);

--
You received this message because you are subscribed to the Google Groups "google-guice" group.
To post to this group, send email to google...@googlegroups.com.
To unsubscribe from this group, send email to google-guice...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/google-guice?hl=en.

Daniel Zwolenski

unread,
Dec 11, 2011, 4:10:19 PM12/11/11
to google...@googlegroups.com
Thanks Willi, that solved my problem! I was looking for a simple annotation or annotation parameter (which would still seem nicer, but I can live with it) so I was heading down the wrong path.

Cheers!


2011/12/11 Willi Schönborn <w.scho...@googlemail.com>
Reply all
Reply to author
Forward
0 new messages