Java 是否可以将特定类型的不可变集绑定到Guice中的实例?
我是Guice的完全初学者,并试图实现以下目标:Java 是否可以将特定类型的不可变集绑定到Guice中的实例?,java,dependency-injection,java-8,singleton,guice,Java,Dependency Injection,Java 8,Singleton,Guice,我是Guice的完全初学者,并试图实现以下目标: public class Apple { private final Integer size; public Apple(Integer size) { this.size = size; } } public abstract class AppleModule { protected AppleModule() { ImmutableSet<Integer> siz
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);
}
}
公共类苹果{
私有最终整数大小;
公共苹果(整数大小){
这个。大小=大小;
}
}
公共抽象类AppleModule{
受保护的AppleModule(){
ImmutableSet size=ImmutableSet.of(1,2,3);
ImmutableSet apples=size.stream().map(Apple::new).collect(ImmutableSet.toImmutableSet());
bind(newimmutableset(){}).toInstance(apples);
}
}
所以每次我声明类似ImmutableSet-apppleBasket代码>,我得到了相同的列表对象。(但其他类型的ImmutableSet
s仍表现正常)
但是上面的代码不适用于bind(…)
说明类必须声明为抽象类或实现抽象方法错误
注意:在编写问题时,我简化了我正在编写的代码,因此上面的代码可能无法开箱编译 首先,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
ImmutableSet<Apple> provideAppleBasket() {
ImmutableSet<Integer> sizes = ImmutableSet.of(1, 2, 3);
ImmutableSet<Apple> apples = sizes.stream().map(Apple::new)
.collect(ImmutableSet.toImmutableSet());
return apples;
}