§Java Configuration API の移行
クラス play.Configuration
は、Typesafe Config を直接使用することが推奨され、非推奨になりました。したがって、play.Configuration
を使用する代わりに、com.typesafe.config.Config
を使用する必要があります。以下に例を示します。
以前
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;
}
}
§Configの値は常に定義されている必要がある
Config
と play.Configuration
のAPIの主な違いは、デフォルト値をどのように処理するかです。Typesafe Config は、デフォルト値を含め、すべての設定キーを .conf
ファイルで宣言する必要があると提唱しています。
Play自体は、可能なすべての設定のデフォルト値を宣言するために reference.conf
ファイルを使用しています。欠落している値を処理する手間を避けるために、ライブラリを配布する場合は同じことができます。設定が読み込まれると、application.conf
ファイルが reference.conf
設定の上に重ねられます。以下に例を示します。
以前(configuration
は play.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.hasPath
または Config.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
このドキュメントにエラーを見つけましたか?このページのソースコードはこちらにあります。ドキュメントのガイドラインを読んだ後、プルリクエストを自由に送信してください。質問や共有できるアドバイスがありますか?コミュニティフォーラムにアクセスして、コミュニティとの会話を始めましょう。