我想创建一个基本功能为列表的对象,我将使用Guice将其注入到我的服务中
public class MyRepository {
List<MyInterface> list = new ArrayList<>();
public void add(MyInterface obj){
list.add(obj);
}
public List<MyInterface> get(){
return list;
}
}
然后我将使用注入从不同的点添加元素到这个列表
public class ObjectA implements MyInterface {
@Inject
public ObjectA(MyRepository myRepository){
myRepository.add(this);
}
}
我的问题是,我想确保MyRepository仅在所有潜在订阅者添加后才在服务中使用。
Multibinder不适用,因为它需要一些特定的方法
有办法吗?由于
如果您正在使用multibinder
,您可能想要做这样的事情?你不想使用static
打破@Inject MyRepository repository;
逻辑下游。
假设您已经正确配置了multibinder
,那么您的存储库应该是这样工作的:
class MyRepository {
Set<MyInterface> interfaces;
@Inject
public MyRepository(Set<MyInterface> interfaces) {
// Here you can do some things like re-applying the interfaces to
// a TreeSet (for example) if you needed to control priority.
this.interfaces = interfaces;
}
public Set<Permissions> getPermissions(final User user) {
// However you want to iterate through the interfaces
return interfaces.stream()
.flatMap(i -> i.getPermissions(user)) // maybe?
.collect(Collectors.toSet());
}
}
你可以有:
- 不同的接口迭代方法
- 根据其他接口对接口进行过滤。例如,如果一个
MyInterface
也扩展了MyOtherInterface
如果我遗漏了什么,请更新/评论,我们可以整理。