Profiles In dagger

500 Views Asked by At

I am new to dagger and I am searching for how can we implement functionality like spring profiles in dagger-2.x. I want different beans for my devo and prod environments, but I am using dagger framework with Java.

@Provides
@Singleton
public void providesDaggerCoffeeShopClient(Stage stage) {
  DaggerCoffeeShop.builder()
    .dripCoffeeModule(new DripCoffeeModule())
    .qualifier(stage)
    .build();
}

Here, I want to skip this bean creation if stage is "Devo". Any help will be appreciated.

1

There are 1 best solutions below

0
On

Well. I have met this question 2 days ago. And since performed research about this matter. I was looking for a solution that would allow me to be able to run application with different profiles passed as a system property on the application run like:

java -Denv=local-dev-env -jar java-app.jar

The only appropriate solution I was able to find is to follow the oficial documentation testing guide: https://dagger.dev/dev-guide/testing and devide my one module into different modules, in particular I had to separate and substitute data base dependency when I want to run my app locally avoiding connection to real DB and executing any command against real DB. And when I run my app I perform check on system property like:

public boolean isLocalDevEnv() {
        return Environments.LOCAL_DEV.envName.equals(System.getProperty("env", Environments.PRODUCTION.envName));
    }

and if the system property DOES NOT contain the property I am looking for, then I create the PRODUCTION instance of my component (that is configured to use production modules):

DaggerMyAppComponent.create()

Which approximately looks like:

@Component(modules = {MyAppModule.class, DaoModule.class})
@Singleton
public interface MyAppComponent {...}

otherwise, I create loca-dev-env version of the component that uses the version of the module that produces mock of Dao that would be creating real connection to real Data Base otherwise:

DaggerMyAppLocalDevEnvComponent.create()

Which approximately looks like:

@Component(modules = {MyAppModule.class, DaoMockModule.class})
@Singleton
public interface MyAppLocalDevEnvComponent {...}

Hope it was clear, so just think of Spring Profiles for dagger 2 from the perspective of system properties and programmatic decision making. This approach definitely requires ALOT of boilerplate code in comparison to Spring's Profiles implementation, but it is the only viable approach I was able to come up with.

Hope it helps.