@ConfigurationProperties

@ConfigurationProperties クラスは、あるプレフィックスの下のすべてのプロパティを、型付きの一つのオブジェクトにまとめます。各フィールドは、フィールド名をケバブケースにしたキーからバインドされ (maxBasketSize は shop.max-basket-size を読みます)、フィールドの型に変換され、オブジェクトは他の Bean と同じように注入されます。

アノテーションは spring_core_dart にあり、spring_boot_dart が起動時にバインドとバリデーションを行います。

使う理由

@Value は一つのキーを読みます。10 個の設定を持つ機能には、それらを列挙し、型を付け、チェックする場所が必要です。

例

# lib/resources/application.yml
shop:
  title: NEON Books
  max-basket-size: 20
  checkout-timeout: 30s
  currencies: [EUR, USD]
  payment:
    provider: stripe
    timeout: 5s
  servers:
    - name: eu
      url: https://eu.neon.books
    - name: us
      url: https://us.neon.books
  headers:
    X-Shop: neon
  warehouses:
    berlin:
      capacity: 5000
      open: true
@ConfigurationProperties('shop')
@Validated()
class ShopProperties {
  /// The shop's name, shown in the header.
  @NotBlank()
  String title = 'Shop';                              // shop.title

  /// The most books in one basket.
  @Min(1)
  @Max(100)
  int maxBasketSize = 10;                             // shop.max-basket-size

  Duration checkoutTimeout = const Duration(minutes: 1);
  List<String> currencies = ['EUR'];                  // カンマ区切りのリスト、または [0]、[1]
  Payment payment = Payment();                        // ネストしたオブジェクト
  List<Server> servers = [];                          // オブジェクトのリスト
  Map<String, String> headers = {};                   // 値のマップ
  Map<String, Warehouse> warehouses = {};             // オブジェクトのマップ
}

class Payment {
  String provider = 'none';
  Duration timeout = const Duration(seconds: 10);
}

class Server {
  String name = '';
  String url = '';
}

class Warehouse {
  int capacity = 0;
  bool open = false;
}

@Service()
class Shipping {
  Shipping(this.shop);

  final ShopProperties shop;

  int capacityOf(String city) => shop.warehouses[city]?.capacity ?? 0;
}

@EnableConfigurationProperties も @ConfigurationPropertiesScan も不要です。アノテーションがクラスを Bean にし、ジェネレーターがそのイントロスペクションを書き出します。フィールドはゲッターやセッターなしで直接バインドされます。

パラメーター

パラメーター デフォルト 意味
prefix 必須 キーに共通する先頭部分。正規形で書く: shop、my-app、spring.main。'' はプレフィックスのないキーをバインドする
name クラスから Bean の名前
ignoreUnknownFields true false にすると、プレフィックスの下で何にもバインドされないキーがあれば起動を止める: The elements [db.urll] were left unbound. OS の環境変数はチェックされない
ignoreInvalidFields false true にすると、値を変換できないとき、失敗する代わりにフィールドのデフォルトを保つ

バインドのルール

イミュータブルなクラス: コンストラクターバインド

唯一のコンストラクターがパラメーターを持つクラスは、そのコンストラクターを通してバインドされます。ネストしたクラスも同様です。これはイミュータブルなクラスに対する Spring Boot 3 のデフォルトです。

@ConfigurationProperties('pool')
class PoolProperties {
  const PoolProperties(
    this.url, {                                   // 必須: pool.url を設定しなければならない
    @DefaultValue('10') required this.maxSize,    // 設定されていなければ 10
    this.timeout = const Duration(seconds: 5),    // Dart のデフォルトも使える
    this.owner,                                   // nullable: 設定されていなければ null
    this.replicas = const [],                     // pool.replicas[0].host=...
  });

  final String url;
  final int maxSize;
  final Duration timeout;
  final String? owner;
  final List<Endpoint> replicas;
}

プロパティのないパラメーターは、@DefaultValue、なければ Dart のデフォルト、それもなければ nullable の場合は null を取ります。そのどれもない必須の非 nullable パラメーターは起動を止めます: pool.url: no value bound for the required constructor parameter 'url' of PoolProperties。ないコレクションは空になり、ないネストしたオブジェクトはそれ自身のデフォルトで生成されます。

その他のアノテーション

アノテーション 付ける場所 効果
@Name('import') フィールドまたはコンストラクターのパラメーター 別のキーからバインドする。キーが Dart のキーワード (import、default) の場合に必要
@DefaultValue('10') コンストラクターのパラメーター キーが設定されていないときに使う値。プロパティの値として書く
@DurationUnit(ChronoUnit.seconds) Duration フィールド 単なる数値をその単位で読む (app.timeout=60 は 60 秒)。月と年はない
@DataSizeUnit(DataUnit.megabytes) DataSize フィールド 単なる数値をその単位で読む
@RawValue() String フィールド プレースホルダーを解決しない
@Range(min, max)、@WarnValues([...], 'why')、@PropertyValues([...]) フィールド エディター用のメタデータのための範囲、警告する値、許可する値

@Bean メソッドに付ける

@Bean メソッドに @ConfigurationProperties('pool') を付けると、メソッドが返すオブジェクトをバインドします。他のパッケージのクラスでもかまいません (ジェネレーターがそのイントロスペクションを書き出します)。メソッドに @Validated() を付けると、それを検証します。

@Configuration()
class PoolConfiguration {
  // Spring について何も知らないライブラリのクラスに pool.* をバインドする。
  @Bean()
  @ConfigurationProperties('pool')
  PoolSettings poolSettings() => PoolSettings();
}

起動時のバリデーション

@Validated() を付けると、値がバインドされた後に制約アノテーションがチェックされます。不正な値は、キーを示すレポートとともに起動を止めます。

Binding to target properties under 'shop' failed:

  - shop.max-basket-size: must be greater than or equal to 1 (was "0")

バインドされたオブジェクトを検証する方法は 3 つあります。

@ConfigurationProperties クラスの @Validated() は、メソッドバリデーションではなく「バインド後に検証する」ことを意味します。Flutter アプリでは @Size は @SizeConstraint という名前です。バリデーション を参照してください。

Binder: クラスのない構造

Binder は、設定の一部を必要に応じてある型にバインドします。ルールは同じです。設定を読むスターターのように、リストやマップを一度だけ必要とするコードのためのものです。

final binder = Binder.get(environment);

// YAML のリスト、インデックス付きのキー、カンマ区切りのリスト: どれも List になる。
final hosts = binder
    .bind('shop.hosts', const ListType(ClassType<String>()))
    .orElse(const []);

final limits = binder
    .bind('shop.limits', const MapType(ClassType<String>(), ClassType<int>()))
    .orElse(const {});

BindResult には get、isBound、orElse、orElseGet、orElseThrow、ifBound、map があります。bind に渡した BindHandler は、各プロパティについて通知を受けます (onStart、onSuccess、onFailure、onFinish)。その onFailure(name, error) は失敗を数えるかどうかを返します (false はプロパティをバインドしないままにします)。

エディター用のメタデータ

ジェネレーターは、クラスのキー、型、デフォルト、/// コメントを lib/spring_gen/spring_metadata.json に書き出します。spring-configuration-metadata.json に当たるものです。手で書くものは何もありません。マップのフィールドは headers.*、クラスのリストは servers[*].url として列挙されます。メタデータ を参照してください。

Spring (Java) との対応

@ConfigurationProperties("shop")
@Validated
public class ShopProperties {
  @NotBlank private String title = "Shop";
  @Min(1) @Max(100) private int maxBasketSize = 10;
  // getters and setters
}

@SpringBootApplication
@ConfigurationPropertiesScan
class NeonBooks { ... }

違い:

関連項目