Playframework settings depending on environment

2020-05-24 06:11发布

问题:

I'm using playframework 2.1-RC2. First of all I've seen all the similar questions, so I followed the common instruction of separating application.conf file per environment. So I have application.test.conf and I run tests this way:

play -Dconfig.file=./conf/application.test.conf "test"

I tried different combinations, like

play -Dconfig.file=./conf/application.test.conf ~test

or

play -Dconfig.file=conf/application.test.conf ~test

Still no luck, it just does not get picked, default one (application.conf) is instead.

From the other side, if I do

play -Dconfig.file=./conf/application.dev.conf "run"

then application picks the right config.

So how can I specify the test configuration file?

回答1:

I found the most robust way to specifiy this in a cross-platform compatible manner is to include it directly in the Build.scala:

val main = play.Project(appName, appVersion, appDependencies).settings(
    javaOptions in Test += "-Dconfig.file=conf/test.conf",
    ...
)

Bonus: configure once and forget ;-)



回答2:

Another approach is to override method on GlobalSettings / Global named onLoadConfig and that enables you to have control where your app will look for your configuration.

So in one of our application I have this setup below for my conf/ folder.

 conf/application.conf --> configurations common for all environment
 conf/dev/application.conf --> configurations for development environment
 conf/test/application.conf --> configurations for testing environment
 conf/prod/application.conf --> configurations for production environment

With that, you are able to implement inheritance like setup for configuration, you have common and 3 others for specific environment mode.

The code inside your onLoadConfig method should just load main configuration and set correct fallback configuration specific to your environment then return the configuration instance like below:

**return new Configuration(baseConfig.withFallback(envConfig));**

Try check this blog post for complete snippet of the code.

I hope this helps.