What is a good way to set up a project in Scala which uses different configuration depending on environments.
I need to specifically have different databases for development, test and production environment (similar to what is done in Rails)
What is a good way to set up a project in Scala which uses different configuration depending on environments.
I need to specifically have different databases for development, test and production environment (similar to what is done in Rails)
I wasn't happy with how Daniel Cukiers solution did not allow defaults and overrides, so I changed it around to make full use of those.
The only configuration you have to do is set a ENVIRONMENT variable on the system (defaults to 'dev' if none is set)
(Java solution, compatible with Scala):
This allows a single reference.conf in a library looking like this:
Usage:
Another strategy I'm using consists of using includes. I usually store my DEV settings in the default
application.conf
file then I create a new conf file for other environments and include the default one.Let's say my DEV conf
application.conf
looks like this:Then for the PROD, I could have another file called
prod.conf
:Note that I override only the settings that change in the PROD environment (
some-other-setting
is thus the same as in DEV).The config bootstrap code doesn't test anything
To switch from the DEV to the PROD conf, simply pass a system property with the name of the config file to load:
In DEV, no need to pass it since
application.conf
will be loaded by default.So here we're using Typesafe Config's default loading mechanism to achieve this.
I've created a simple project to demonstrate this technique. Feel free to clone and experiment.
Use typesafe Config. Create a Config object like this:
Then create the
application.conf
file insrc/main/resources
folder:Now from anywhere in your application, you can access configuration:
Config().getString("your_app.databaseUrl")
If you have your environment set up (e.g.
export SCALA_ENV=test
) when you run your application, it will consider the right configuration section. The default is developmentHere is a solution that is in Scala, allows for overrides, and doesn't rely on an external library.
If
PROJECT_ENV
is set totest
,Config.get("somethingElse")
will return"hi"
. Otherwise, it will return"whatever"
.Running
PROJECT_ENV=test sbt test
will get old fast, so you can have SBT set the environment variable when the test suite is run.Here is how to override the existing config.
Here's a link to the full blog post I wrote on this topic.