Spring Boot @ConfigurationProperties POJO を生成する
アプリ設定の JSON / YAML ペイロードから、ネストグループ、リスト、バリデーションを備えた Spring Boot @ConfigurationProperties クラスを生成します。
詳細な説明
JSON から Spring Boot @ConfigurationProperties
Spring Boot の @ConfigurationProperties は、外部設定(application.yml、環境変数、JSON 設定サーバ)を強く型付けされた Java POJO にバインドします。設定が YAML でも構造的には JSON と等価なので、本ジェネレーターをそのまま使えます。
設定 JSON の例
{
"app": {
"name": "OrderService",
"version": "2.4.1",
"timeout_seconds": 30,
"feature_flags": {
"use_new_payments": true,
"enable_audit_log": false
},
"database": {
"url": "jdbc:postgresql://localhost:5432/orders",
"pool_size": 20
},
"trusted_origins": [
"https://app.example.com",
"https://admin.example.com"
]
}
}
生成される POJO
生成後、Spring のアノテーションで配線します。
package com.example.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import java.util.Map;
@ConfigurationProperties(prefix = "app")
public class AppProperties {
private String name;
private String version;
@JsonProperty("timeout_seconds")
private Integer timeoutSeconds;
@JsonProperty("feature_flags")
private Map<String, Boolean> featureFlags;
private Database database;
@JsonProperty("trusted_origins")
private List<String> trustedOrigins;
// アクセサ
}
public class Database {
private String url;
@JsonProperty("pool_size")
private Integer poolSize;
// アクセサ
}
等価な application.yml
app:
name: OrderService
version: 2.4.1
timeout-seconds: 30
feature-flags:
use-new-payments: true
enable-audit-log: false
database:
url: jdbc:postgresql://localhost:5432/orders
pool-size: 20
trusted-origins:
- https://app.example.com
- https://admin.example.com
注意:@ConfigurationProperties バインダーは YAML の kebab-case を camelCase Java フィールドに自動マッピングします。@JsonProperty は同じ POJO を JSON からデシリアライズするときにのみ必要です。
バインダーを有効化
メインアプリケーションクラスで次のように指定します。
@SpringBootApplication
@EnableConfigurationProperties(AppProperties.class)
public class App {
public static void main(String[] args) { SpringApplication.run(App.class, args); }
}
バリデーションを追加
JSR-380(jakarta.validation)アノテーションで起動時に設定を検証できます。
@NotBlank
private String name;
@Min(1) @Max(300)
private Integer timeoutSeconds;
@NotEmpty
private List<String> trustedOrigins;
クラスに @Validated を付けると、制約違反時に起動を失敗させられます。
設定用 record
Spring Boot 3 は @ConfigurationProperties で record をサポートします。
@ConfigurationProperties(prefix = "app")
public record AppProperties(String name, String version,
Integer timeoutSeconds, Database database) {}
record にすると設定が不変になり、起動時設定としてはこれが正しいデフォルトです。
ユースケース
Spring Boot マイクロサービスは関心事ごとに(DB、メッセージング、フィーチャーフラグ、外部 API キーなど)トップレベルの @ConfigurationProperties クラスを持つのが普通です。サンプル JSON 設定から POJO を生成することで、YAML 構造を手動で写し取る面倒な作業を省けます。