Spring Value annotation默认为表达式?

时间:2016-08-18 18:27:05

标签: java spring

考虑file

中的以下属性
defaultProperty="default"
overrideProperty="override"

我的班级首先需要检查overrideProperty是否可用并使用它,否则回退到defaultProperty

我尝试这样做

MyClass {

 @Value("${overrideProperty: defaultProperty}")
 String tokenizationAlgorithm;
}

这不起作用,因为我得到的是defaultProperty不是 default(这是值)

如何将表达式放在@Value注释的默认值部分?

1 个答案:

答案 0 :(得分:2)

使用以下语法:

@Value("${overrideProperty:${defaultProperty}}")

${overrideProperty:${defaultProperty}}将传递给PropertyPlaceholderHelperreplacePlaceholders方法,该方法会将格式为${name}的所有占位符替换为相应的值。

请注意,由于parseStringValue方法的递归特性,${defaultProperty}值将在${overrideProperty}之前得到解决。因此,即使在提供${overrideProperty}的情况下,您也应始终拥有默认值。此外,您可以为默认值提供默认值!

@Value("${overrideProperty:${defaultProperty:literallyDefault}}")

此外,介意差距

@Value("${overrideProperty: defaultProperty}")
                           ^ This space will be placed before your default value
相关问题