@Value默认值的使用方法

时间:2025-02-13 19:03:50
@Value("${address.host1}")
private String host1;

上面的两行代码表示,从或者yml文件中读取address.host1的值赋给host1属性,但有些情况我们需要一个默认值,我们可以用下面的方法来实现

@Value("${address.host1:127.0.0.1}")
private String host1;

通过在address.host1后面加冒号,后面即可设置默认值,此处我的默认值为127.0.0.1

@Value("${address.host1:127.0.0.1}")
private String host1;

又或者我们想让host1属性的默认值为空字符串(即“”

@Value("${address.host1:}")
private String host1;

这样host1的默认值就是“”了;