How to inject a Provider using Guice
I want to inject a Provider<T>
, in something开发者_运维百科 like this:
class Work {
Provider<Tool> provider;
@Inject
Work (Provider<Tool> provider) { this.provider = provider; }
}
My Module
looks something like this:
protected void configure () {
bind (Tool.class).to(MyTool.class);
// Q: How do I bind this:
bind (new TypeLiteral<Provider<Tool>> {}).to (????);
// A: Turns out deleting these last 3 lines makes everything just right.
}
I want to inject a Provider<T>
because Work
class needs to create more Tool
objects and work with them. Also, I'm not sure there really needs to be a binding for TypeLiteral<Provider<Tool>>
but I think it's closest approach for this case.
Have you tried just not binding it? I'd expect Guice to just build you a provider which resolves the non-provider binding each time.
From "Injecting Providers":
For every binding, annotated or not, the injector has a built-in binding for its provider.
So I think that just binding Tool
will be enough. It's at least worth a try :) (I'd love to sound more confident, but I don't have as much Guice-fu as I'd like...)
精彩评论