Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play Framework 2.4.1: How to get configuration values just after configuration file has been loaded

I need to read some configuration values just after the configuration file has been loaded but before the application actually starts.

In Play 2.3.x I used to override GlobalSettings.onLoadConfig, which is deprecated in Play 2.4.x. The official documentation says one should use GuiceApplicationBuilder.loadConfig instead.

Again, the documentation is a bit poor and I was unable to find more details or an example... so any help would be really appreciated.

like image 915
j3d Avatar asked Jun 30 '15 20:06

j3d


1 Answers

1. Before app starts

If you need to read configuration before app starts, this approach can be used:

modules/CustomApplicationLoader.scala:

package modules

import play.api.ApplicationLoader
import play.api.Configuration
import play.api.inject._
import play.api.inject.guice._

class CustomApplicationLoader extends GuiceApplicationLoader() {
  override def builder(context: ApplicationLoader.Context): GuiceApplicationBuilder = {
    println(context.initialConfiguration) // <- the configuration
    initialBuilder
      .in(context.environment)
      .loadConfig(context.initialConfiguration)
      .overrides(overrides(context): _*)
  }
}

conf/application.conf has the following added:

play.application.loader = "modules.CustomApplicationLoader"

With that, I see the following in console (snipped as too long):

Configuration(Config(SimpleConfigObject({"akka":{"actor":{"creation-timeout":"20s"...

Source: documentation.

2. Not before app starts

If you don't need to read configuration before app starts, this approach can be used instead: (it's so embarrassingly simple) the Module bindings method takes a Play Environment and Configuration for you to read:

class HelloModule extends Module {
  def bindings(environment: Environment,
               configuration: Configuration) = {
    println(configuration) // <- the configuration
    Seq(
      bind[Hello].qualifiedWith("en").to[EnglishHello],
      bind[Hello].qualifiedWith("de").to[GermanHello]
    )
  }
}
like image 119
bjfletcher Avatar answered Oct 10 '22 12:10

bjfletcher