【发布时间】:2021-02-25 08:08:37
【问题描述】:
您可以通过多种方式使用 Spring 创建ConfigurationProperties-Objects。
一种方法是将@ConfigurationProperties-Annotation 添加到@Bean-Declaration 中,如下所示:
@Bean
@ConfigurationProperties("my.property.group")
public MyProperties myProperties() {
return new MyProperties();
}
它将从MyProperties-class 创建一个bean,然后使用它的setter 用配置文件中的值填充它的成员。
您也可以像这样直接在MyProperties-Object 上添加注释:
@ConfigurationProperties("my.property.group")
public class MyProperties {
@Getter @Setter private String myFirstValue;
@Getter @Setter private String mySecondValue;
}
通过将@EnableConfigurationProperties(MyProperties.class) 放置到任何加载的配置来创建它。
也可以使用@ConstructorBinding以不可变的方式创建此类
@ConfigurationProperties("my.property.group")
@ConstructorBinding
public class MyProperties {
@Getter private final String myFirstValue;
@Getter private final String mySecondValue;
public MyProperties(String myFirstValue, String mySecondValue) {
this.myFirstValue = myFirstValue;
this.mySecondValue = mySecondValue;
}
}
但是如何结合第一个 @Bean 方法创建不可变的 ConfigurationProperties?
我尝试过这样的事情:
@Bean
@ConfigurationProperties("my.property.group")
// @ConstructorBinding <---- This is not applicable to methods
public MyProperties myProperties(String myFirstValue, String mySecondValue) {
return new MyProperties(myFirstValue, mySecondValue);
}
这告诉我,它无法自动装配参数,我将考虑声明一些 String 类型的 bean
【问题讨论】: