首页 > 解决方案 > 来自应用程序属性的 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

我将如何解决这个问题?

谢谢!

巴特

标签: javaspring-bootproperties

解决方案


@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;
    }
}

推荐阅读