文件

§Java 設定 API 遷移

play.Configuration 類別已棄用,建議直接使用 Typesafe Config。因此,您現在必須使用 com.typesafe.config.Config,而不是 play.Configuration。例如

之前

import play.Configuration;
public class Foo {
    private final Configuration configuration;

    @javax.inject.Inject
    public Foo(Configuration configuration) {
        this.configuration = configuration;
    }
}

之後

import com.typesafe.config.Config;

public class Foo {
    private final Config config;

    @javax.inject.Inject
    public Foo(Config config) {
        this.config = config;
    }
}

§設定值應始終定義

Configplay.Configuration API 之間的主要差異在於如何處理預設值。 Typesafe Config 主張所有設定金鑰都必須在您的 .conf 檔案中宣告,包括預設值。

Play 本身使用 reference.conf 檔案來宣告所有可能組態的預設值。若要避免處理遺失值的麻煩,如果您正在散布程式庫,您可以執行相同的動作。當讀取組態時,application.conf 檔案會疊加在 reference.conf 組態之上。例如

在 (configurationplay.Configuration) 之前

// Here we have the default values inside the code, which is not the idiomatic way when using Typesafe Config.
Long timeout = configuration.getMilliseconds("my.service.timeout", 5000); // 5 seconds

之後

# This is declared in `conf/reference.conf`.
my.service.timeout = 5 seconds

最後,您可以在 application.conf 檔案中覆寫值

# This will override the value declared in reference.conf
my.service.timeout = 10 seconds

這在建立模組時特別有用,因為您的模組可以提供容易覆寫的參考值。您的 Java 程式碼會如下所示

Long timeout = config.getDuration("my.service.timeout", TimeUnit.MILLISECONDS);

其中 config 是您的 com.typesafe.config.Config 實例。

§手動檢查值

如果您不想要或由於某些原因無法提供預設值,您可以使用 Config.hasPathConfig.hasPathOrNull 在存取值之前檢查值是否已組態。如果組態是必要的,但您無法提供參考 (預設) 值,這是比較好的選項

import com.typesafe.config.Config;
import com.typesafe.config.ConfigException;

public class EmailServerConfig {

    private static final String SERVER_ADDRESS_KEY = "my.smtp.server.address";

    private final Config config;

    @javax.inject.Inject
    public EmailServerConfig(Config config) {
        this.config = config;
    }

    // The relevant code is here. First use `hasPath` to check if the configuration
    // exists and, if not, throw an exception.
    public String getSmtpAddress() {
        if (config.hasPath(SERVER_ADDRESS_KEY)) {
            return config.getString(SERVER_ADDRESS_KEY);
        } else {
            throw new ConfigException.Missing(SERVER_ADDRESS_KEY);
        }
    }
}

下一步:Play 2.5


在此文件中找到錯誤?此頁面的原始程式碼可以在 這裡 找到。在閱讀 文件指南 之後,請隨時提交拉取請求。有問題或建議要分享嗎?請前往 我們的社群論壇 與社群展開對話。