我们正在使用 Spring Boot 创建 API,并且有一些配置将在下面的 docker 容器广告中作为 env 提供:
config:
host: ${HOST}
apiKey: ${API_KEY}
我的服务类中需要此主机和 API 密钥才能进行外部 API 调用。
有没有办法在 Spring boot 中直接从 application.yaml 创建
Record
类,如下所示?
public record Config(String host, String apiKey){}
在主类上添加
@ConfigurationPropertiesScan
像这样创建类,这应该可以工作
@ConfigurationProperties(value = "config")
public record Config(String host, String apiKey) { }
或者如果您还想要默认设置
@ConfigurationProperties(value = "config")
public record Config(String host, String apiKey) {
@ConstructorBinding
public Config(String host, String apiKey) {
this.host = Optional.ofNullable(host).orElse("localhost");
this.apiKey = Optional.ofNullable(apiKey).orElse("secret");
}
}