java - 来自应用程序属性的 Spring Boot 不可变列表
问题描述
我在从属性文件(yaml 文件)创建不可修改的列表时有点迷失了。这有效:
@Getter
@ConfigurationProperties(prefix = "device")
@Configuration
public class DeviceConfiguration {
private final List<String> identifiers;
@Value("${device.somekey.disabled:false}")
private final boolean disabled;
@Value("${device.someotherkey.number}")
private final int number;
}
但我希望列表是不可修改的。此列表上的后续代码更改可能会在流程中产生非常严重的错误。所以我认为这样的事情会起作用,但它没有:
@Getter
@ConfigurationProperties(prefix = "device")
@Configuration
public class DeviceConfiguration {
private final List<String> identifiers;
private final boolean disabled;
private final int number;
@ConstructorBinding
public DeviceConfiguration(final List<String> identifiers,
@Value("${device.somekey.disabled:false}") final boolean disabled,
@Value("${device.someotherkey.number}") final int number) {
this.identifiers = Collections.unmodifiableList(identifiers);
this.userkeySigningDisabled = userkeySigningDisabled;
this.number = number;
}
}
如果我将@ConstructorBinding 添加到我得到的类中:
Cannot bind @ConfigurationProperties for bean 'DeviceConfiguration'.
Ensure that @ConstructorBinding has not been applied to regular bean
如果我将 @ConstructorBinding 添加到构造函数(如示例中),我会得到:
Failed to bind properties under 'device' ...
Property: device.identifiers[5]
Value: SomeValue
Origin: class path resource [application.yaml] - 424:7
Reason: No setter found for property: identifiers
我将如何解决这个问题?
谢谢!
巴特
解决方案
您@ConstructorBinding
以错误的方式使用。该文档描述了正确的用法。注释需要放在类级别:
@Getter
@ConstructorBinding
@ConfigurationProperties(prefix = "device")
public class DeviceConfiguration {
private final List<String> identifiers;
private final boolean disabled;
private final int number;
public DeviceConfiguration(final List<String> identifiers,
@Value("${device.somekey.disabled:false}") final boolean disabled,
@Value("${device.someotherkey.number}") final int number) {
this.identifiers = Collections.unmodifiableList(identifiers);
this.userkeySigningDisabled = userkeySigningDisabled;
this.number = number;
}
}
推荐阅读
- f# - F#中教堂数字的减法
- python - Matplotlib Python 3 没有从非原点开始绘制箭头
- python - 如何在 tkinter 中使用文本图像作为按钮?
- python - 在 django 2 中找不到页面(404)
- angular - 分层店铺组织
- java - 无效的 Lambda 表达式
- react-native - 嵌套的水平滚动视图不起作用 - React Native
- javascript - role.setColor 不是 discord.js 上的函数
- python - 如何根据特定数量的字符比较字符串
- javascript - 当我单击 eventlistner 按钮时,我想刷新复选框