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

百般思念 提交于 2020-01-13 10:17:07

问题


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.


回答1:


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]
    )
  }
}


来源:https://stackoverflow.com/questions/31147865/play-framework-2-4-1-how-to-get-configuration-values-just-after-configuration-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!