首页 > 解决方案 > 是否可以将特定类型的不可变集绑定到 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其他类型的 s 仍然表现正常)

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

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

标签: javadependency-injectionjava-8singletonguice

解决方案


首先,Guice模块必须扩展AbstractModule类并覆盖其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 文档获取更多信息。


推荐阅读