Class gắn @ConfigurationProperties("prefix") phải trở thành bean thì Spring mới bind. Có ba cách:
- @EnableConfigurationProperties(MyProperties.class) trên một class @Configuration.
- @ConfigurationPropertiesScan trên class main (quét cả package).
- Gắn thêm @Component lên chính class đó.
@ConfigurationProperties("app.payment")
public class PaymentProperties {
private final Duration timeout;
private final String callbackUrl;
// single parameterized constructor -> constructor binding, fields can be final
public PaymentProperties(Duration timeout, String callbackUrl) {
this.timeout = timeout;
this.callbackUrl = callbackUrl;
}
}Relaxed binding: tên property trong Environment không cần trùng khít tên field. app.payment.callback-url, app.payment.callbackUrl, app.payment.callback_url và biến môi trường APP_PAYMENT_CALLBACKURL đều bind vào callbackUrl. Đây là lý do khai báo trong file YAML nên dùng dạng kebab-case, còn khi truyền qua env var trên server thì dùng dạng in hoa gạch dưới.
Thêm @Validated cùng các constraint (@NotBlank, @Min) lên class properties để app fail lúc khởi động nếu config sai, thay vì lỗi lúc chạy.