【发布时间】: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