2014-10-16 604 views
4

我試圖將3.0.5版本的spring版本升級到3.2.11。SpEL - 空值比較

我進入用SpeI麻煩時表達式進行比較這樣的空值:在

new SpelExpressionParser().parseExpression("null < 7").getValue();  

結果的上述代碼結果

  • 假,使用版本3.0.5時
  • 真的,當使用版本3.2.11時,這是不正確的,由於我的意見

這種不同的行爲的原因是,在StandartTypeComparator類,它在內部使用的規劃環境地政司,也有不同的實現方法比較的:

  • 版本3.0.5

    public int compare(Object left, Object right) throws SpelEvaluationException { 
    // If one is null, check if the other is 
    if (left == null) { 
        return right == null ? 0 : 1; 
    } else if (right == null) { 
        return -1; // left cannot be null 
    } 
    
  • 版本3.2.11

    public int compare(Object left, Object right) throws SpelEvaluationException { 
    // If one is null, check if the other is 
    if (left == null) { 
        return right == null ? 0 : -1; 
    } else if (right == null) { 
        return 1; // left cannot be null 
    } 
    

當我看到上面的代碼,我可以看到,運行

new SpelExpressionParser().parseExpression("7 < null").getValue();  

將導致:

  • 真實的,使用的版本3.0.5,這是不正確的,因爲我的意見時
  • 假的,使用的版本3.2.11時

這基本上意味着交換比較邏輯和行爲的重大變化,並對我們的應用程序有很大的影響。

可能存在概念上的問題 - 比較兩個值時,假設它們具有可比性,它們可以相等,小於或大於另一個。但是,在這個意義上,空值不可比較,除了空值正確嗎?

這是一個錯誤?

當使用<,>,==,< =,> =運算符與另一個非空值比較時,空值比較曾經假設爲TRUE?

回答

0

這不是一個bug,它是Spring團隊的設計行爲。

Spring document

大於/小於號對空比較遵循一個簡單的規則:null被視爲沒有在這裏(即不爲零)。因此,任何其他值總是大於空(X> null始終爲真),並且其他值永遠不會小於空(X < null始終爲false)。

如果這種行爲會影響你的邏輯,我覺得你可以不喜歡以下:

" first == null ? false : second == null ? false : first < second "