gpt4 book ai didi

java - Guice 迭代多个绑定(bind)

转载 作者:行者123 更新时间:2023-12-02 07:01:44 26 4
gpt4 key购买 nike

如果我有一个接口(interface) IBaseFunction 和该接口(interface)的多个实现。如何迭代调用每个即上的方法的绑定(bind)

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);
...

}
}

我需要在每个绑定(bind)上调用函数“publish()”(使处理程序在总线上可用)

我可以像这样单独调用每个绑定(bind)上的函数:-

ExDeleteFunction functionExDelete = injector.getInstance( ExDeleteFunction.class);
ExDeleteFunction.publish();
ExAddFunction functionExAdd = injector.getInstance( ExAddFunction.class);
ExAddFunction.publish();

但是我想做的是迭代这些并调用所有这些函数的“发布”函数,有没有办法做到这一点?也许使用injector.getAllBindings()?像这样的东西:-

  Injector injector = Guice.createInjector( new ServicesModule() );

Map<Key<?>, Binding<?>> bindings = injector.getAllBindings();
for (Binding<?> binding : bindings.values()) {
Key<?> key = binding.getKey();
...??

或者有更简单的方法吗?

最佳答案

是的,有更简单的方法,称为 Multibindings 。有了这个,你将能够做类似的事情

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();
}
}

但是,这样可能无法单独注入(inject)你的函数(我不知道,你需要测试一下);您还可以查看MapBinder .

关于java - Guice 迭代多个绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16588605/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com