我是 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;
的东西时,我得到了相同的列表对象注入(inject)。 (但其他类型的 ImmutableSet
仍然表现正常)
但是上面的代码不适用于 bind(...)
说Class must either be declared abstract or implement abstract method error
注意:我在编写问题时简化了我正在处理的代码,因此上面的代码可能无法直接编译。
最佳答案
首先,Guice
模块必须扩展AbstractModule
类并覆盖其configure()
方法。其次,如果你想绑定(bind)泛型类型,你需要使用 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了解更多信息。
关于java - 是否可以将特定类型的不可变集绑定(bind)到 Guice 中的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56644580/