使用来自两个不同范围的提供程序 [英] Using the provider from two different scopes

查看:48
本文介绍了使用来自两个不同范围的提供程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Guice存在以下问题:单项服务注入了上下文相关信息的提供者。到目前为止,上下文仅与servlet请求相关,因此我使用了@RequestScoped提供程序,并且正在将该提供程序注入服务中,如下所示:

I have the following problem with Guice: a singleton service, is injected with provider of context-sensitive information. Until now, context was related only to servlet requests, so I used a @RequestScoped provider, and I was injecting this provider in service like so:

@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(..)。我编写了一个自定义范围(Giuse doc的BatchScoped几乎完全相同的副本),以使每个Task在其自己的范围内运行。现在的问题是-如何制作BatchScoped ContextProvider并配置Guice以使用它?

That works fine. Now, I'm working on adding background task processing to the application. Background tasks are not initiated from web-requests, so I can not use ServletScopes.scopeRequest(..). I have written a custom scope (almost exact copy of BatchScoped from Giuce doc) to make each Task run in it's own scope. Now the question is - how to make BatchScoped ContextProvider and configure Guice to use it?

我已经尝试通过绑定EDSL:

I've made this attempt with binding 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行告诉我在第1行已经配置了对IContext的绑定。

but Guice tells me at line 2 that 'A binding to IContext was already configured at line 1'.

问题是:用Guice进行这种注射的正确方法是什么?

The question is: what's the right way of doing such injection with Guice?

推荐答案

类似的问题:获取相同类型的多个guice单例

通常,这里的问题是您想要将相同的类绑定到两个不同的提供程序(和作用域,但这实际上是无关紧要的)。仅当您对每个绑定注解使用唯一的绑定注解时,才有可能,例如:

In general the problem here is that you want to bind the same class to two different providers (and scopes, but that's actually beside the point). That is only possible if you use unique binding annotations for each one, like so:

bind(IContext.class)
    .annotatedWith(MyAnnotation1.class)
    .toProvider(ContextProvider.class)
    .in(RequestScoped.class);
bind(IContext.class)
    .annotatedWith(MyAnnotation2.class)
    .toProvider(BatchContextProvider.class)
    .in(BatchScoped.class);

并更改注入位置以包括相关注释:

And change injection sites to include relevant annotation:

@Inject
@MyAnnotationX
private Provider<IContext> contextProvider;

这篇关于使用来自两个不同范围的提供程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆