Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject Dependencies at runtime using Google Guice

Tags:

guice

I'm thinking of using Guice for DI in my app where I should be able to swap the implementations at runtime. An example is provided below to illustrate the requirement:

class ValidationEngine {
   public void validate(ValidationService vs) {}
}

class Client1_ValidationService implements ValidationService {}
class Client2_ValidationService implements ValidationService {}

One of the above implementation should be bound to validate function at runtime based on client name, say Client1 or Client2

I thought of changing the ValidationEngine like this:

class ValidationEngine {   
    @Inject 
    @Named("vServicee") ValidationService vs;

    public void validate() {
         vs.validate()
    }
}

The problem with the above approach is that the parameter to the @Named annotation is static; in fact annotations don't accept runtime values. Are there any other approaches in Guice to solve this kind of problems?

like image 403
giri_col Avatar asked Feb 01 '26 06:02

giri_col


1 Answers

You can just pass in configuration information to your Guice module via it's constructor.

Pseudocode:

main() { // your main method
    flags = parseFlags()
    injector = guice.createInjector(new MyModule(flags.validator))
}

MyModule { // your guice module
    constructor(validator): this.validator = validator;
    configure() {
        Class<ValidatorService> client_validator;
        if this.validator == KNOWN_CLIENT1:
            client_validator = Client1_ValidationService.class
        else:
            client_validator = Client2_ValidationService.class
        bind(ValidationService.class).to(client_validator);
    }
}

Guice cautions against this, as it increases the surface area for you to test. https://github.com/google/guice/wiki/AvoidConditionalLogicInModules

like image 54
Justin Abrahms Avatar answered Feb 03 '26 09:02

Justin Abrahms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!