我在使用 Guice 时遇到以下问题:单例服务注入(inject)了上下文相关信息的提供者。到目前为止,上下文仅与 servlet 请求相关,因此我使用了 @RequestScoped 提供程序,并且将该提供程序注入(inject)到服务中,如下所示:
@RequestScoped
public class ContextProvider<IContext> implements Provider<IContext> {
@Override
public IContext get() { ... } // returns context
}
@Singleton
public class ServiceImpl implements IService {
@Inject
private Provider<IContext> contextProvider;
}
效果很好。现在,我正在努力向应用程序添加后台任务处理。后台任务不是从 Web 请求启动的,因此我无法使用 ServletScopes.scopeRequest(..)。我编写了一个自定义范围(几乎是来自 Giuce 文档的 BatchScoped 的精确副本),以使每个任务在其自己的范围内运行。现在的问题是 - 如何制作 BatchScoped ContextProvider 并配置 Guice 来使用它?
我已经通过绑定(bind) EDSL 进行了此尝试:
line 1 : bind(IContext.class).toProvider(ContextProvider.class).in(RequestScoped.class);
line 2 : bind(IContext.class).toProvider(BatchContextProvider.class).in(BatchScoped.class);
但 Guice 在第 2 行告诉我“与 IContext 的绑定(bind)已在第 1 行配置”。
问题是:使用 Guice 进行此类注入(inject)的正确方法是什么?
最佳答案
类似的问题:Getting multiple guice singletons of the same type
一般来说,这里的问题是您想要将同一个类绑定(bind)到两个不同的提供程序(和范围,但这实际上不是重点)。只有当您为每个绑定(bind)使用唯一的绑定(bind)注释时,这才有可能,如下所示:
bind(IContext.class)
.annotatedWith(MyAnnotation1.class)
.toProvider(ContextProvider.class)
.in(RequestScoped.class);
bind(IContext.class)
.annotatedWith(MyAnnotation2.class)
.toProvider(BatchContextProvider.class)
.in(BatchScoped.class);
并更改注入(inject)站点以包含相关注释:
@Inject
@MyAnnotationX
private Provider<IContext> contextProvider;
关于java - 使用来自两个不同范围的提供程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27336407/