如何使用 Guice 注入 Provider

发布于 12-06 00:47 字数 715 浏览 0 评论 0 原文

我想注入一个 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心的位置 2024-12-13 00:47:35

您是否尝试过不绑定它?我期望 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":

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文