我需要在加载配置文件之后但在应用程序实际启动之前读取一些配置值。
在Play 2.3.x中,我曾经覆盖GlobalSettings.onLoadConfig
,这在Play 2.4.x中已弃用。官方文档说明应该使用GuiceApplicationBuilder.loadConfig
。
同样,文档有点差,我无法找到更多细节或示例......所以任何帮助都会非常感激。
答案 0 :(得分:5)
如果您需要在应用启动之前阅读配置,可以使用此方法:
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
添加了以下内容:
play.application.loader = "modules.CustomApplicationLoader"
有了这个,我在控制台中看到以下内容(剪断太长):
Configuration(Config(SimpleConfigObject({"akka":{"actor":{"creation-timeout":"20s"...
来源:documentation。
如果您在应用程序启动之前不需要读取配置,则可以使用此方法:(这非常简单)Module
绑定方法需要Play环境和配置才能阅读:
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]
)
}
}