[英]Guice iterating over multiple bindings
If I have an interface IBaseFunction and multiple implementations for this interface. 如果我有一个接口IBaseFunction和这个接口的多个实现。 How can I iterate over the bindings calling a method on each ie 我如何迭代调用每个ie上的方法的绑定
public class MyModule extends AbstractModule {
@Override
protected void configure() {
bind( IBaseFunction.class).annotatedWith( ExDelete.class).to( ExDeleteFunction.class);
bind( IBaseFunction.class).annotatedWith( ExAdd.class).to( ExAddFunction.class);
...
}
}
I need to call a function 'publish() on each binding (makes the handler available on a bus) 我需要在每个绑定上调用一个函数'publish()(使得处理程序在总线上可用)
I could call the function on each binding individually like this :- 我可以像这样单独调用每个绑定上的函数: -
ExDeleteFunction functionExDelete = injector.getInstance( ExDeleteFunction.class);
ExDeleteFunction.publish();
ExAddFunction functionExAdd = injector.getInstance( ExAddFunction.class);
ExAddFunction.publish();
However what I would like to do is iterate over these and call the 'publish' function on all of them, is there a way of doing this ? 然而,我想要做的是迭代这些并在所有这些上调用'publish'函数,有没有办法做到这一点? Maybe using injector.getAllBindings() ? 也许使用injector.getAllBindings()? Something like this :- 像这样: -
Injector injector = Guice.createInjector( new ServicesModule() );
Map<Key<?>, Binding<?>> bindings = injector.getAllBindings();
for (Binding<?> binding : bindings.values()) {
Key<?> key = binding.getKey();
...??
or is there a simpler way ? 还是有更简单的方法?
Yes, there is much simpler way, called Multibindings . 是的,有更简单的方法,称为Multibindings 。 With this you will be able to do something like 有了这个,你就可以做类似的事情
public class BaseFunctionsModule extends AbstractModule {
@Override
public void configure() {
Multibinder<BaseFunction> multibinder = Multibinder.newSetBinder(binder(), BaseFunction.class);
mapBinder.addBinding().to(ExDeleteFunction.class);
mapBinder.addBinding().to(ExAddFunction.class);
// others
}
}
public static void main(String[] args) {
Injector injector = Guice.createInjector(new BaseFunctionsModule());
Set<BaseFunction> functions = injector.getInstance(new TypeLiteral<Set<BaseFunction>>() {});
for (BaseFunction function : functions) {
function.publish();
}
}
However, in this way it may be not possible to inject your functions separately (I don't know, you need to test it); 但是,通过这种方式,可能无法单独注入您的功能(我不知道,您需要对其进行测试); you may also look into MapBinder . 您也可以查看MapBinder 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.