Play Framework 2.4.1:如何在加载配置文件后立即获取配置值 [英] Play Framework 2.4.1: How to get configuration values just after configuration file has been loaded

查看:190
本文介绍了Play Framework 2.4.1:如何在加载配置文件后立即获取配置值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在加载配置文件之后但在应用程序实际启动之前读取一些配置值.

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

在Play 2.3.x中,我曾经覆盖GlobalSettings.onLoadConfig,但在Play 2.4.x中已弃用.官方文档说应该使用GuiceApplicationBuilder.loadConfig代替.

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添加了以下内容:

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"...

来源:文档.

如果您不需要在启动应用之前阅读配置,则可以改用这种方法:(它非常简单)Module绑定方法采用Play环境和配置供您阅读:

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

这篇关于Play Framework 2.4.1:如何在加载配置文件后立即获取配置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆