I'm relatively new to using Dagger and I have been reading up on the documentation here - https://google.github.io/dagger/users-guide . I was previously using Spring for DI. One thing which I was still not sure was - How to read environment variables in Dagger.
For example, in Spring, I'd just do:
@Value("${envVariable}")
private String myEnvVariable;
@Bean
public MyClass myclass() {
return new MyClass().builder().property(myEnvVariable).build();
}
I'm not sure if I'm somehow conflating the usage of Dagger as for reading environment variables.
I was assuming that in Dagger I'd have a Module which constructs the MyClass and then I'd use the @Inject annotation to inject the dependency, but wasn't sure how I'd get the value of the environment variable.
I ended up defining a method which would do something like this:
@Provides
@Named("ENV_VARIABLE_NAME")
@Singleton
public String getMyEnv() {
return System.getenv("ENV_VARIABLE_NAME");
}
For usage, I have the @Named annotation, and therefore I'd just inject a String with the Named annotation in my other Module classes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.