我想注入一个 Provider
,如下所示:
class Work {
Provider<Tool> provider;
@Inject
Work (Provider<Tool> provider) { this.provider = provider; }
}
我的 Module
看起来像这样:
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.
}
我想注入一个 Provider
code> 因为 Work
类需要创建更多 Tool
对象并使用它们。另外,我不确定是否真的需要绑定 TypeLiteral>
但我认为这是最适合这种情况的方法。
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.
您是否尝试过不绑定它?我期望 Guice 只为您构建一个每次都解析非提供者绑定的提供者。
来自“注入提供程序”:
所以我认为仅仅绑定
Tool
就足够了。这至少值得一试:)(我想让自己听起来更自信,但我没有我想要的那么多 Guice-fu...)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":
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...)