所有属性的@Value的默认值

问题描述 投票:0回答:1

如果我们没有一个属性的值,我们会得到下面的错误。这个错误可以通过设置一个冒号来避免。: 是否有办法为所有属性设置默认值。有没有一种方法可以为所有的属性设置默认值,这样我的应用程序就不需要依赖开发者来指定了。:?

Could not resolve placeholder

如果有更好的方法来解决这个问题,请告诉我。

@Component
public class PropertiesDemo {

    @Value("${some.key1:my default here}")
    private String stringWithDefaultValue;

    @Value("${some.key2:}")
    private String stringWithBlankDefaultValue;

    @Value("${some.key3:}")
    private Boolean booleanWithBlankDefaultValue;

    @Value("${some.key4:}")
    private Integer intWithBlankDefaultValue;

    @PostConstruct
    public void printValues() {
        System.out.println("stringWithDefaultValue :: "+stringWithDefaultValue);
        System.out.println("stringWithBlankDefaultValue :: "+stringWithBlankDefaultValue);
        System.out.println("booleanWithBlankDefaultValue :: "+booleanWithBlankDefaultValue);
        System.out.println("intWithBlankDefaultValue :: "+intWithBlankDefaultValue);
    }

}
stringWithDefaultValue :: my default here
stringWithBlankDefaultValue :: 
booleanWithBlankDefaultValue :: null
intWithBlankDefaultValue :: null
spring properties default-value
1个回答
0
投票

正如@M.Deinum所评论的那样,没有标准的方法可以做到这一点。

类型之间的转换通常由 Converter 的实现。这里的用例有点不寻常,在你的特殊情况下一定有更多的内容。

您可能会对以下内容感兴趣 Spring Boot中的类型安全配置属性 直接在类型、丰富类型、验证、环境绑定上提供默认值。

© www.soinside.com 2019 - 2024. All rights reserved.