Search code examples
dependency-injectioncdiguiceweld

CDI and multiple instances


I'm just investigating possibilities of DI frameworks and I made some stupid example for it. I have simple service.

public class Service implements ServiceI {
    private Source source;

    private Translator translator;

    @Inject
    public Service(Translator translator, Source source) {
        this.translator = translator;
        this.source = source;
    }

I want to have two instances of this service one which is initiated with TranslatorA and SourceA and second which will be injected with different values.

How can one have two instances with different beans injected inside?

I'm interested in ways how to achieve this in both Guice and Weld CDI.

So far I created multiple Guice modules and specify bind-to in it as I like. But I'm not completely sure if it is correct way. And this completely fails in CDI as there are no modules.

I thing that having multiple instances must be pretty common case or am I wrong?


Solution

  • The way you would do this with CDI is by setting up a producers for translator and source. It's the only way to control which implementations are used for injection at runtime. The implementation details may vary based on your exact needs but something like this should get you on the right track

    @Produces
    public Translator produceTranslator(@Dependent TranslatorA implA, @Dependent TranslatorB implB) {
        return checkRuntimeCondition() ? implA : implB;
    }
    

    And the same for the source. That way when you inject Service, CDI'll call the producer method for each parameter and use a runtime condition to select the implementation. YMMV on the details, you may need to set up additional qualifiers to avoid ambiguity.