Java Guice Provider

时间:2015-10-28 02:02:30

标签: java guice

我有一个小问题,我无法想出来挽救我的生命。

基本上我需要随时使用guice动态注册类,然后循环遍历它们。

让我们说这是我的班级注册策略,但这些策略可以通过应用程序运行随时添加。

// 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类,以便我可以投射它们吗?

我需要为同一个实例添加多个绑定,但它需要动态完成,而不是在configure中使用bind方法,但另一种方式则能够找到所有这些策略并执行它们。

1 个答案:

答案 0 :(得分:2)

如果您真的需要在应用程序生命周期中的“任何时间”发生,那么Guice然后我认为您将需要某种Guice-aware Factory。即。

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

如果在初始化阶段之后它不是“动态的”那么你就是在我认为的“multibinder”之后。