【发布时间】:2014-11-26 02:11:01
【问题描述】:
Spring Boot 的 @ConfigurationProperties 注释是否可以具有不可变(最终)字段?下面的例子
@ConfigurationProperties(prefix = "example")
public final class MyProps {
private final String neededProperty;
public MyProps(String neededProperty) {
this.neededProperty = neededProperty;
}
public String getNeededProperty() { .. }
}
到目前为止我尝试过的方法:
- 使用两个构造函数创建
MyProps类的@Bean- 提供两个构造函数:空的和带有
neededProperty参数的构造函数 - bean 是用
new MyProps()创建的 - 字段中的结果为
null
- 提供两个构造函数:空的和带有
- 使用
@ComponentScan和@Component提供MyPropsbean。- 结果为@987654332@ ->
NoSuchMethodException: MyProps.<init>()
- 结果为@987654332@ ->
我让它工作的唯一方法是为每个非最终字段提供 getter/setter。
【问题讨论】:
-
据我所知,您尝试做的事情不会开箱即用。
-
这很可悲。当然,我总是可以通过使用带有
@Value注释的构造函数参数来使用普通 Spring 来实现。不过,如果 Spring Boot 也支持这个就好了。 -
我在源代码上取得了一个小高峰,但支持您所要求的内容并非易事。当然,我不是 Spring 内部的专家,所以我可能会遗漏一些明显的东西
-
这不是您正在寻找的,但可能会对这个现有的 Spring Boot 问题感兴趣:github.com/spring-projects/spring-boot/issues/1254
-
cmets 中提出的解决方案也可以解决我的问题。如果设置器不可见,则配置属性将无法修改而无需诉诸暴力:)
标签: java spring spring-boot properties-file