【问题标题】:Default value for @Value for all properties所有属性的 @Value 的默认值
【发布时间】:2020-05-23 10:17:44
【问题描述】:

如果我们没有属性的值,我们会得到以下错误。可以通过设置冒号: (带或不带默认值)来避免此错误。有没有一种方法可以为所有属性设置默认值,这样我的应用程序就不需要依赖开发人员指定:

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

【问题讨论】:

  • 能否添加您的代码?
  • 没有设置默认值的标准方法。 int、long、String、map 的默认设置是什么……所有这些属性都可以转换为其他属性。虽然foobar 可能是String 的有效默认值,但它如何成为数字类型的默认值?
  • @MukeshKeshu,@M。 Deinum,我在上面添加了一个工作代码 sn-p。如果您在任何 spring 应用程序中运行它,它将打印如上所示的输出。在上面的例子中,如果开发者忘记输入:,应用程序将无法启动。有没有办法为所有属性设置默认值?使用上述模式,Spring 采用声明的字段的数据类型来选择默认值。

标签: spring properties default-value


【解决方案1】:

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

类型之间的转换通常由Converter 实现覆盖。这里的用例有点不寻常,在您的特定情况下肯定还有更多。

您可能对type-safe configuration properties in Spring Boot 感兴趣,它直接提供类型的默认值、丰富的类型、验证、来自环境的绑定。

【讨论】:

  • 这些选项中的任何一个怎么样? 1)我们能否在服务器启动失败的情况下捕获Could not resolve placeholder values异常并妥善处理? 2) 在课堂级别使用@ConfigurationProperties@Validated 怎么样。这样我可以实现一个验证器,以便服务器启动不受影响?我的最终目标是不想停止服务器,而是要捕获此类无效属性异常并进行适当处理。我使用配置服务器,因此如果服务器启动,我总是可以将属性文件更新为正确的值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-16
  • 1970-01-01
  • 2016-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多