【问题标题】:Is there a way to bind a couple of instances to many different keys in Guice?有没有办法将几个实例绑定到 Guice 中的许多不同键?
【发布时间】:2015-06-02 10:57:14
【问题描述】:

我们需要在一些对象的许多类型之间创建一些映射,用枚举值描述:

public enum ObjectType {
Type1,Type2,Type3,Type4,Type5...TypeN
}

...和

  1. 用于这些类型的多个策略实例
  2. 或者,例如,与提到的 ObjectTypes 相关的布尔值

来自 Guice 的 MapBinder 可用于此目的,以及标准的 HashMap 以及来自 google 收藏的一些复杂地图。

我想要的是找到适合这种匹配“值”的“低密度”结构的东西。我想看看类似的东西

binder.addBinding(ObjectType.Type1,ObjectType.Type2...ObjectType.Type6).toInstance(Boolean.TRUE)
or
binder.addBinding(ObjectType.Type1,ObjectType.Type2...ObjectType.Type6).toInstance(new SomeStrategyForFirstSixObjectType())

有什么建议吗?

【问题讨论】:

标签: java collections guava guice


【解决方案1】:

最简单的方法是遍历值:

for (ObjectType type : ObjectType.values()) {
  // Assumes you've created a binding annotation @YourAnnotation(ObjectType) along
  // with an implementation called YourAnnotationImpl.
  bind(Boolean.class)
      .annotatedWith(new YourAnnotationImpl(type))
      .toInstance(Boolean.TRUE));

  // Now you can inject "@YourAnnotation(Type1) Boolean yourValue" and so on.
}

然而,尽管它可能对某些用途有意义,但您可能不希望 Guice 中的每个值都有单独的布尔绑定——尤其是在绑定多个相关值时。相反,您可以考虑将所有内容集中到一个 TypeConfiguration(例如)中,您可以按上述方式绑定每个类型,并在测试中替换为 FakeTypeConfiguration

您还可以将所有内容收集在一起并将其绑定到Map

bind(new TypeLiteral<Map<ObjectType, Boolean>> {})
    .toInstance(ImmutableMaps.<ObjectType, Boolean>newBuilder()
        .add(Type1, TRUE)
        .add(Type2, TRUE)
        // [snip, you could replace with a for-loop or pre-built map]
        .build());

// Now you can inject "Map<ObjectType, Boolean>".

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多