java - 是否可以将特定类型的不可变集绑定到 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
注意:我在编写问题时简化了我正在处理的代码,所以上面的代码可能无法立即编译。
解决方案
首先,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 文档获取更多信息。
推荐阅读
- angular - agm-map 更改整个页面的字体
- r - 将图例添加到组合的线和条形图 ggplot
- android - Android - java,将位置数据从一个类发送到活动视图
- regex - 如何修复“正则表达式中未转义的左大括号在正则表达式中是非法的”错误?
- coq - Coq:一元到二进制的转换
- node.js - 部署的 Nodejs 服务在 Azure Web App 上不起作用
- r - 当我将标签添加到 geom_bar 时,如何阻止图形发生变化?
- selenium - 无头镀铬慢启动
- python - python中是否有换行符,就像
HTML中有a - amazon-web-services - 有没有办法暂时停止 AWS Kinesis Stream?