Guice:一个“提供者”(T< T>用于多个实现 [英] Guice: One "Provider<T>" for multiple implementations

查看:98
本文介绍了Guice:一个“提供者”(T< T>用于多个实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接口有20个左右的注释实现。如果我在编译时知道我需要什么,我可以注入正确的,但现在我需要根据运行时参数动态注入一个。



据了解文档,我必须使用20个左右的 Provider< T> 注入,然后使用我需要的,对我来说似乎相当过分。有没有办法像 inst(Provider< T>)。get(MyAnnotation.class)来绑定一个特定的实现,然后只有那个提供者注入我的课堂

解决方案

注入 MapBinder



在您的模块中,将绑定加载到 MapBinder 中,然后使运行时参数也可注入。该示例基于文档中的一个:

  public class SnacksModule extends AbstractModule {
protected void configure() {
MapBinder< String,Snack> mapbinder
= MapBinder.newMapBinder(binder(),String.class,Snack.class);
mapbinder.addBinding(twix)。to(Twix.class);
mapbinder.addBinding(snickers)。(Snickers.class);
mapbinder.addBinding(skittles)。(Skittles.class);
}
}

然后,在你的对象中,注入 Map 和参数。对于这个例子,我将假设你绑定了一个 java.util.Properties 为您的运行时参数:

  @ Inject 
public MyObject(Map< String,Provider< Snack>> snackProviderMap,属性属性){
String snackType =(String)properties.get(snackType);
提供者<小吃> = snackProviderMap.get(property);

//等
}

请注意,相同的 MapBinder 您可以注入简单的 Map< String,Snack> Map<字符串,提供者< Snack>> ; Guice绑定两者。


I have an interface that has 20 or so annotated implementations. I can inject the correct one if I know which I need at compile time, but I now need to dynamically inject one based on runtime parameters.

As I understood the documentation, I would have to use 20 or so Provider<T> injections and then use the one I need, which seems rather excessive to me. Is there a way to have something like an inst(Provider<T>).get(MyAnnotation.class) to bind a specific implementation, and then have only that Provider injected into my class?

解决方案

Inject a MapBinder.

In your module, load the bindings into the MapBinder, then make your runtime parameters injectable as well. This example is based on the one in the documentation:

public class SnacksModule extends AbstractModule {
  protected void configure() {
    MapBinder<String, Snack> mapbinder
           = MapBinder.newMapBinder(binder(), String.class, Snack.class);
    mapbinder.addBinding("twix").to(Twix.class);
    mapbinder.addBinding("snickers").to(Snickers.class);
    mapbinder.addBinding("skittles").to(Skittles.class);
  }
}

Then, in your object, inject the Map and the parameter. For this example I will assume you've bound a java.util.Properties for your runtime parameters:

@Inject
public MyObject(Map<String, Provider<Snack>> snackProviderMap, Properties properties) {
  String snackType = (String) properties.get("snackType");
  Provider<Snack> = snackProviderMap.get(property);

  // etc.
}

Note, with the same MapBinder you can inject either a simple Map<String, Snack> or a Map<String, Provider<Snack>>; Guice binds both.

这篇关于Guice:一个“提供者”(T&lt; T&gt;用于多个实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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