是否可以将特定类型的不可变集绑定到 Guice 中的实例?

Is it possible to bind an immutable set of certain type to an instance in Guice?

我是 Guice 的完全初学者,正在努力实现以下目标:

public class Apple {

    private final Integer size;
    public Apple(Integer size) {
        this.size = size;
    }
}

public abstract class AppleModule {
   protected AppleModule() {

      ImmutableSet<Integer> sizes = ImmutableSet.of(1, 2, 3); 
      ImmutableSet<Apple> apples = sizes.stream().map(Apple::new).collect(ImmutableSet.toImmutableSet());
      bind(new ImmutableSet<Apple>(){}).toInstance(apples);

   }
}

这样每次我声明类似 ImmutableSet<Apple> apppleBasket; 的东西时,我都会注入相同的列表对象。 (但 ImmutableSet 其他类型的行为仍然正常)

但是上面的代码不适用于 bind(...)Class must either be declared abstract or implement abstract method error

注意:我在编写问题时简化了我正在处理的代码,因此上面的代码可能无法立即编译。

首先,Guice 模块必须扩展 AbstractModule class 并覆盖其 configure() 方法。其次,如果你想绑定泛型类型,你需要使用TypeLiteral.

public class AppleModule extends AbstractModule {

  @Override
  public void configure() {
    ImmutableSet<Integer> sizes = ImmutableSet.of(1, 2, 3);
    ImmutableSet<Apple> apples = sizes.stream().map(Apple::new)
      .collect(ImmutableSet.toImmutableSet());

    bind(new TypeLiteral<ImmutableSet<Apple>>(){}).toInstance(apples);
  }
}

或者,例如,您可以使用 @Provides 方法。

  @Provides
  ImmutableSet<Apple> provideAppleBasket() {
    ImmutableSet<Integer> sizes = ImmutableSet.of(1, 2, 3);
    ImmutableSet<Apple> apples = sizes.stream().map(Apple::new)
      .collect(ImmutableSet.toImmutableSet());
    return apples;
  }

请使用 Guice documentation 获取更多信息。