对 spring ConfigurationProperties 子类使用构造函数注入

Art*_*hur 6 java spring dependency-injection immutability

我正在查看这个https://www.baeldung.com/configuration-properties-in-spring-boot并想知道是否可以对这些使用构造函数注入来强制执行一些不变性属性。

例如,是否可以这样做:

@Component
@ConfigurationProperties("my-config")
public class MyConfig {

    private final List<String> values;

    public MyConfig(@Value("${values}") List<String> values) {
        this.values = ImmutableList.copyOf(values);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在我的 yml 配置中有

my-config.values:
  - foo
  - bar
Run Code Online (Sandbox Code Playgroud)

但我收到此错误:

java.lang.IllegalArgumentException: Could not resolve placeholder 'values' in string value "${values}"
Run Code Online (Sandbox Code Playgroud)

nek*_*739 5

spring boot 是可能的,因为版本 2.2.0 文档在这里:构造函数绑定添加新注释@ConstructorBinding