代码之家  ›  专栏  ›  技术社区  ›  Steffen Harbich

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

  •  1
  • Steffen Harbich  · 技术社区  · 6 年前

    让我们考虑以下测试:

    @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.Spring Frask.表达式.SPEL.Stult.SPelExalp.GETValk(SPelExalp.java:328) 在 Org.ExpRealTest.TestSAMeExpRealDealEntLogObjutCub类(ExpRevestValuestStest.java:36)

    原因:java.lang.ClassCastException:java.lang.long无法强制转换 到spel.ex2.getValue(未知源)处的java.lang.string Org.Spring Frask.表达式.SPEL.Stult.SPelExalp.GETValk(SPelExalp.java:318) …31个以上

    这对我来说是意外的,并且在文档中没有找到关于这个约束的任何内容。我在这里做错什么了吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Gary Russell    6 年前

    你应该使用 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
    
    }