[英]Java Guice Provider
我有一個小問題,我無法解決以挽救我的生命。
基本上我需要隨時使用 guice 動態注冊類,然后循環遍歷它們。
假設這是我注冊 Strategies 的課程,但可以通過運行的應用程序隨時添加這些策略。
// Strategy registration may happen anytime, this is just an example
strategyManager.register(ExampleStrategy1.class);
strategyManager.register(ExampleStrategy2.class);
StrategyImpl 類
public class StrategyImpl implements Strategy {
@Override
public void register(Class<? extends StrategyDispatcher> strat) {
//Add this class into provider or create an instance for it and add it into guice but how?
}
@Override
public void dispatchStrategy() {
//Find all strategies and execute them
}
}
我試過使用提供者,但不知道如何將注冊的類添加到提供者中並全部檢索它們?
@Override
protected void configure() {
bind(Strategy.class).toProvider(StrategyProvider.class);
}
我的提供者類總是得到相同的實例
public class StrategyProvider implements Provider<StrategyDispatcher> {
public LogManager get() {
return new StrategyDispatcherImpl();
}
}
我添加的策略擴展了 StrategyDispatcherImpl 類,以便我可以投射它們?
我需要向同一個實例添加多個綁定,但它需要動態完成,而不是在配置中使用綁定方法,而是另一種方式,然后能夠找到所有這些策略並執行它們。
如果你真的需要它在應用程序生命周期中的“任何時間”發生,那么 Guice 那么我認為你將需要某種 Guice-aware Factory。 IE
public class TestStuff {
@Test
public void testDynamicCreation() {
Injector injector = Guice.createInjector();
StrategyManager manager = injector.getInstance(StrategyManager.class);
Hello hello = injector.getInstance(Hello.class);
manager.doStuff();
assertThat(hello.helloCalled, is(false));
manager.register(Hello.class); // DYNAMIC!!
manager.doStuff();
assertThat(hello.helloCalled, is(true));
}
}
interface Strategy {
void doStuff();
}
@Singleton
class Hello implements Strategy {
boolean helloCalled = false;
public void doStuff() {
helloCalled = true;
}
}
class StrategyManager {
private final Collection<Strategy> strategies = new ArrayList<>();
private final StrategyFactory factory;
@Inject
StrategyManager(StrategyFactory factory) {
this.factory = factory;
}
public void register(Class<? extends Strategy> strat) {
strategies.add(factory.create(strat));
}
public void doStuff() {
for (Strategy s : strategies) {
s.doStuff();
}
}
}
class StrategyFactory {
private final Injector injector;
@Inject
StrategyFactory(Injector injector) {
this.injector = injector;
}
public Strategy create(Class<? extends Strategy> clazz) {
return injector.getInstance(clazz);
}
}
如果在初始化階段之后它不是“動態的”,那么我認為您是在“ 多重綁定器”之后。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.