need some help here. I am wondering is it possible to make google dagger 2 work with external configuration files like yml or xml files? I am working with dagger 2 and sparkjava to construct a REST API service, hence i need a way to configure the ports for embedded jetty.
Asked
Active
Viewed 1,010 times
1 Answers
1
Yes, it is possible. You will need to do the heavy lifting yourself, getting the data from the external configuration files into an internal form you can use and then provide that form to dagger at runtime.
I asked a similar question a while back, and got a good answer. Essentially you need to
- Read in the configuration files in a suitable internal form.
Map<String, String>
is a good choice. - You must provide the map to the module at runtime before the
build()
method is invoked. Dagger helps with the autogenerated code. - For each configuration entry, you need to write a
@Provides
method that looks up in the map provided. Yes, each. No short-cuts.
We've done this in a recent project. A lot of boilerplate but works very well when in place.
See the answer at https://stackoverflow.com/a/18105271/53897 for more details.

Community
- 1
- 1

Thorbjørn Ravn Andersen
- 73,784
- 33
- 194
- 347
-
Why in runtime? Isn't dagger 2 generate all code in compile time? – Divers Feb 17 '17 at 09:44
-
@Divers Yes, but you have to deal with data that is not available yet in your code. You have to write all dagger related code at compile time, but the configuration file contents is not available until runtime. Therefore you need to pass in the contents of the configuration file toi the module (at runtime) and write a provider for each configuration file entry that looks up the entry in said contents. – Thorbjørn Ravn Andersen Feb 17 '17 at 12:35