java - 使用不同的根对象类型调用相同的 Spring EL 表达式失败

标签 java spring 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: An exception occurred whilst evaluating a compiled expression

at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:328) at org.example.ExpressionTest.testSameExpressionDifferentRootObjectClass(ExpressionProvidersTest.java:36)

Caused by: java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.String at spel.Ex2.getValue(Unknown Source) at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:318) ... 31 more

这对我来说是出乎意料的,并且在文档中找不到任何有关此约束的内容。我在这里做错了什么吗?

最佳答案

对于此类情况,您应该使用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

}

关于java - 使用不同的根对象类型调用相同的 Spring EL 表达式失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50568899/

相关文章:

java - 返回特定格式的值(java)

java - 将 HashMap 键与另一个随机 HashMap 键匹配的算法,从不复制值或匹配自身

javascript - 网站和移动应用程序的登录 API 应该相同还是不同?

Spring UriComponents 线程安全

Spring 表达式语言 (SpEL) 与 @Value : dollar vs. 哈希($ vs. #)

spring - 在 Camel Marshal 和 Unmarshal 标签中使用 Spring 表达式语言

java - JFormattedTextField 与 MaskFormatter

java - JPA @JoinTable - 三个 ID 列

spring - 如何创建 Gradle 任务以在 Spring 中仅运行特定的测试

java - SpEL 中的#root 和#this