开发者

How to inject a Provider using Guice

开发者 https://www.devze.com 2023-04-08 09:27 出处:网络
I want to inject a Provider<T>, in something开发者_运维百科 like this: class Work { Provider<Tool> provider;

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...)

0

精彩评论

暂无评论...
验证码 换一张
取 消