2016-08-18 68 views
-1

考慮以下特性在fileSpring的值註釋默認爲表達式嗎?

defaultProperty="default" 
overrideProperty="override" 

我有一個類,首先需要檢查是否overrideProperty可用,並使用它,否則退回上defaultProperty

我試着這樣做的

MyClass { 

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

這是不行的,因爲我得到的回覆是defaultPropertydefault(這是值)

我如何可以把一個表達式@Value註釋的默認值部分?

+1

你嘗試'@Value( 「$ {overrideProperty:$ {defaultProperty}}」)'? –

回答

1

使用以下語法:

@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 
+0

在默認值之前的空間不是強制性的,它的工作也沒有空間 – sanjeevjha

+0

@sanjeevjha我知道這不是強制性的,但它會在實際值之前預先佔用一個不需要的空間,例如, 「某物」會變成「某物」。 –