java - 使用不同的根对象类型调用相同的 Spring EL 表达式失败
问题描述
让我们考虑以下测试:
@Test
public void testSameExpressionDifferentRootObjectClass() {
SpelParserConfiguration config = new SpelParserConfiguration(SpelCompilerMode.IMMEDIATE, Thread.currentThread().getContextClassLoader());
SpelExpressionParser parser = new SpelExpressionParser(config);
StandardEvaluationContext context = new StandardEvaluationContext();
Expression expr = parser.parseExpression("'Test: ' + #root");
assertThat(expr.getValue(context, 42L)).isEqualTo("Test: 42");
assertThat(expr.getValue(context, "string")).isEqualTo("Test: string");
assertThat(expr.getValue(context, 42L)).isEqualTo("Test: 42");
assertThat(expr.getValue(context, "string")).isEqualTo("Test: string");
}
它在第三个断言上失败,但有以下例外:
org.springframework.expression.spel.SpelEvaluationException: EL1072E: 评估编译表达式时发生异常
在 org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:328) 在 org.example.ExpressionTest.testSameExpressionDifferentRootObjectClass(ExpressionProvidersTest.java:36)
原因:java.lang.ClassCastException:java.lang.Long 无法在 org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression. java:318) ... 31 更多
这对我来说是出乎意料的,并且在文档中没有发现有关此约束的任何内容。我在这里做错了吗?
解决方案
对于这种情况,您应该使用MIXED
模式;请参阅 javadocs ...
public enum SpelCompilerMode {
/**
* The compiler is switched off; this is the default.
*/
OFF,
/**
* In immediate mode, expressions are compiled as soon as possible (usually after 1 interpreted run).
* If a compiled expression fails it will throw an exception to the caller.
*/
IMMEDIATE,
/**
* In mixed mode, expression evaluation silently switches between interpreted and compiled over time.
* After a number of runs the expression gets compiled. If it later fails (possibly due to inferred
* type information changing) then that will be caught internally and the system switches back to
* interpreted mode. It may subsequently compile it again later.
*/
MIXED
}
推荐阅读
- c# - C#:并行 foreach 在循环内调用函数
- angular - Angular 6 / Clarity UI - 表单页面验证,上传数据
- pyspark - pyspark中的窗口函数 - 奇怪的行为
- javascript - 访问 react-components 中的文档
- java - Android Volley 无法获取数据作为响应
- c# - 如何识别特定图像中的“绿色”?
- python - 出现错误:TypeError:'float' 类型的对象在 pandas 中没有 len()
- rest - Wire Mock:HTTP 方法 PATCH 不支持输出
- python - Pepper Linux 日志日期格式看起来毫无意义
- tfs - 如何自定义 TFS 构建任务