【问题标题】:SpEL - null value comparisonSpEL - 空值比较
【发布时间】:2014-12-11 21:19:03
【问题描述】:

我正在尝试将 spring 版本从 3.0.5 升级到 3.2.11。

当表达式像这样比较空值时,我遇到了 SpEL 问题:

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

以上代码的结果

  • false,使用版本 3.0.5 时
  • 是的,当使用 3.2.11 版本时,我认为这是不正确的

这种不同行为的原因是在SpEL内部使用的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 版本时,我认为这是不正确的
  • false,使用版本 3.2.11 时

这基本上意味着交换比较逻辑和行为的重大变化,并对我们的应用程序产生重大影响。

可能存在概念问题 - 比较两个值时,假设它们具有可比性,它们可以相等,小于或大于另一个。但是从这个意义上说,空值除了空值之外什么都没有可比性,对吧?

这是一个错误吗?

当使用 、==、= 运算符与另一个非空值进行比较时,空值比较是否假设为 TRUE?

【问题讨论】:

    标签: spring spring-el


    【解决方案1】:

    不是bug,是Spring团队的设计行为。

    来自Spring document

    与 null 的大于/小于比较遵循一个简单的规则:null 在这里被视为无(即不为零)。因此,任何其他值始终大于 null(X > null 始终为真),并且没有其他值永远小于零(X

    如果这种行为影响你的逻辑,我认为你可以这样做:

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

    【讨论】:

      猜你喜欢
      • 2014-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-13
      • 1970-01-01
      • 1970-01-01
      • 2011-01-24
      • 1970-01-01
      相关资源
      最近更新 更多