【问题标题】:Can we evaluate multiple expressions in single line in Spel Expressions. Just like ExpressionFactory我们可以在 Spel Expressions 的单行中评估多个表达式吗?就像 ExpressionFactory
【发布时间】:2021-11-14 22:42:45
【问题描述】:

ExpressionFactory 必须能够处理以下类型的表达式参数输入:

使用相同分隔符的多个表达式(例如${employee.firstName}${employee.lastName}#{employee.firstName}#{employee.lastName})。

我们可以在 java SPEL 中类似地评估多个表达式吗?

我尝试了以下

Expression expressionMulti = parser.parseExpression( "#{#jsonPath(#jsonDataObject,'$.customData.price')}#{#jsonPath(#jsonDataObject,'$.previousResponse')}");

出错了

Exception in thread "main" org.springframework.expression.spel.SpelParseException: Expression [#{#jsonPath(#jsonDataObject,'$.customData.price')}#{#jsonPath(#jsonDataObject,'$.previousResponse')}] @1: EL1043E: Unexpected token. Expected 'identifier' but was 'lcurly({)'

也试过不带分隔符

Expression expressionMulti = parser.parseExpression( "#jsonPath(#jsonDataObject,'$.customData.price')#jsonPath(#jsonDataObject,'$.previousResponse')");
Exception in thread "main" org.springframework.expression.spel.SpelParseException: EL1041E: After parsing a valid expression, there is still more data in the expression: 'hash(#)'

【问题讨论】:

  • 你试过了吗...
  • @M.Deinum 已对其进行了更新
  • 你想要达到什么目的?如果要连接两个结果,请在两者之间使用 +。
  • @M.Deinum 感谢添加 + 确实部分解决了我的问题。我想要实现的是使用第一个表达式的输出来评估第二个表达式。例如:-假设您的购物车中有 N 件商品,并且您使用表达式 Item.price 收集所有价格,现在可以在我的下一个表达式中使用将是 json 数组的 out 对它们求和并找到总数我知道我可以在内置函数中使用 sum。但对于其他情况,是否有可能,或者我是否需要在上下文中单独注册/设置?我正在尝试一次评估多个表达式
  • 您可以使用流并聚合结果。您可以在其中编写java程序。但为什么要为此使用 SPeL?

标签: java spring-boot spring-el


【解决方案1】:

SpEL 只不过是常规 Java 的语法糖。因此,您需要开始考虑它的定义,就像使用常规 Java 代码那样。因此考虑将您的表达式重写为 Java 代码,然后逐段转到 SpEL。

另一方面,如果您的逻辑如此复杂,请考虑提取一些 static 实用方法,这些方法可以通过 T 运算符从 SpEL 中使用:https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#expressions-types

同样的#jsonPath()JsonPathUtils.evaluate()之上的SpEL函数,你可以直接在你自己的static方法中使用。该实现确实可以使用SpelExpressionParser 来评估那些嵌套的动态表达式。顶部表达式只会使用这些参数调用您的静态方法。

【讨论】:

    猜你喜欢
    • 2016-03-18
    • 1970-01-01
    • 2012-03-30
    • 1970-01-01
    • 2011-08-08
    • 2013-11-19
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多