As others have already answered, you can simply use @Inject Injector
because Guice defines the binding itself.
Normally you only need one Injector
in your app, and a static variable is an even easier way to store and access a singleton than injecting it. In our web app, we use stripes-guicer and get the Injector
from its static method GuiceInjectorFactory.getInjector()
when we need it (in our Hibernate interceptor, for example).
I'm a little baffled by the advice that "you shouldn't use Injector directly." How else would I get an instance injected except by calling injector.getInstance()
or injector.injectMembers()
? There is no way. Yes, you can define Provider methods, but they will never be called unless somewhere, something uses an Injector. Yes, there are modules that use the Injector
for you like the ServletModule; you have to create the Injector
yourself, but you can leave it to the ServletModule
after that.
So in some circumstances, you can avoid using the Injector
directly, but that doesn't mean you "shouldn't" use it. If you're using Guice alone without any optional modules, then you "should" be using an Injector
all over the place because there's no other way to trigger injection. (I think developers who spend all day writing code inside frameworks sometimes forget that some people actually instantiate their own objects.)