Search code examples
javaguice

Java Guice: Run time dependency re-wiring


I have several classes StrategyAlpha, StrategyBeta, StrategyOmega that inherit from the Strategy class.

I would like to select the proper child Strategy depending on property of inputs using guice, the dependency injection framework.

Is wiring the dependencies at runtime a bad idea? How can use Guice to do this?


Solution

  • You'd want to bind something like a StrategyProvider which, given inputs, returns the appropriate strategy.

    You could always create a provider - something like:

    @Inject StrategyProvider(@Named("alpha") Strategy alpha, @Named("beta") Strategy beta...) { this.alpha = alpha; this.beta = beta; }

    Strategy get(Parameter a, parameter b) { if (a > 3 && b < 10) { return beta; } else { return alpha; } }

    What the params are, and why would determine whether this makes sense, more than likely.