Saad
Saad

Reputation: 907

Injecting dependency based on a value in config file

I have a class which takes a configuration interface implementation through DI.

@Inject
private PRCConfiguration prcConfig;

There are various implementations of the PRCConfiguration interface. Currently it is injecting the default implementation. I wish to create a value in a config text file which will define what particular implementation of PRCCOnfiguration to inject. I wish the @Inject notation to verify what value is in the config file, and based on that inject the particular implementation.

I believe we can annotate different implementation through qualifiers and then inject, such as

@Inject @NewImplementation 
private PRCConfiguration prcConfig;

But again i am injecting on compiletime through hard coding.

My config file would be something like

"injectconfig":"NewImplementation"

to inject the @NewImplementation implementation, subsequently if i want a different implementation to be injected. I could just change config file value as

"injectconfig":"DifferentImplementation"

and the different implementation will be injected.

Is what i require possible through CDI?

Upvotes: 1

Views: 703

Answers (1)

chkal
chkal

Reputation: 5668

You can use producer methods to achieve something like that.

Basically you just have to create a CDI bean which a method that returns the correct configuration instance and annotate it with @Produces.

Something like this:

@ApplicationScoped
public class ConfigurationProducer {

    @Produces
    @ApplicationScoped
    public PRCConfiguration getConfig() {

        if( someCondition ) {
            return new NewConfigurationImpl();
        }
        else {
            return new OldConfigurationImpl();
        }

    }

}

In this case you should annotated both implementations with @Vetoed or you will get ambiguous dependencies errors. Using @Vetoed on the implementations will tell CDI that using the producer is the only way to obtain PRCConfiguration instances.

Upvotes: 2

Related Questions