Spring Boot 是否可以拥有不可变(最终)字段@ConfigurationProperties
注解?下面的例子
@ConfigurationProperties(prefix = "example")
public final class MyProps {
private final String neededProperty;
public MyProps(String neededProperty) {
this.neededProperty = neededProperty;
}
public String getNeededProperty() { .. }
}
到目前为止我尝试过的方法:
- Creating a
@Bean
of the MyProps
class with two constructors
- 提供两个构造函数:empty 和 with
neededProperty
争论
- 该 bean 是用以下命令创建的
new MyProps()
- 该领域的结果是
null
- Using
@ComponentScan
and @Component
to provide the MyProps
bean.
- 结果是
BeanInstantiationException
-> NoSuchMethodException: MyProps.<init>()
我让它工作的唯一方法是为每个非最终字段提供 getter/setter。
从 Spring Boot 2.2 开始,终于可以定义一个不可变的类了@ConfigurationProperties
.
文档 https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#features.external-config.typesafe-configuration-properties.constructor-binding展示了一个例子。
您只需要声明一个带有要绑定的字段的构造函数(而不是 setter 方式)并添加@ConstructorBinding https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/context/properties/ConstructorBinding.html类级别的注释指示应使用构造函数绑定。
所以你的实际代码没有任何设置器现在就可以了:
@ConstructorBinding
@ConfigurationProperties(prefix = "example")
public final class MyProps {
private final String neededProperty;
public MyProps(String neededProperty) {
this.neededProperty = neededProperty;
}
public String getNeededProperty() { .. }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)