使用Spring EL表达式进行模板化

5

我想使用Spring EL来进行简单的模板化,例如:"Some text: #{从映射中获取的某些动态值}"。但在我的情况下,文档中的示例并不适用,因为它只适用于从映射中获取值:

    Map<String, Object> data = new HashMap<String, Object>();
    data.put("property", 123);

    String message = "#data['property']";

    ExpressionParser parser = new SpelExpressionParser();
    StandardEvaluationContext context = new StandardEvaluationContext();
    context.setVariable("data", data);

    System.out.println(parser.parseExpression(message).getValue(context, String.class));

在这种情况下,输出结果为123,但是String message = "Some text: #data['property']";却引发了异常。
org.springframework.expression.spel.SpelParseException: EL1041E:(pos 5): After parsing a valid expression, there is still more data in the expression: 'text'
at org.springframework.expression.spel.standard.InternalSpelExpressionParser.doParseExpression(InternalSpelExpressionParser.java:129)
at org.springframework.expression.spel.standard.SpelExpressionParser.doParseExpression(SpelExpressionParser.java:60)
at org.springframework.expression.spel.standard.SpelExpressionParser.doParseExpression(SpelExpressionParser.java:32)
at org.springframework.expression.common.TemplateAwareExpressionParser.parseExpression(TemplateAwareExpressionParser.java:76)
at org.springframework.expression.common.TemplateAwareExpressionParser.parseExpression(TemplateAwareExpressionParser.java:62)

我的错误在哪里?

2个回答

4

文字需要是字面意思。

在Java中,您现在拥有的内容将如下所示...

String s = some text: data.get("property");

如果你在编写Java代码,需要使用以下语法才能编译通过...

...这很显然是无法编译通过的。

String s = "some text: " + data.get("property");

所以你需要在SpEL中使用相应的等价物...

"'Some text: ' + #data['property']"

3
作为替代方案,您可能想使用表达式模板中提到的TemplateParserContext。那么您的示例将如下所示:
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("property", 123);

        String message = "Some text: #{#data['property']}";

        ExpressionParser parser = new SpelExpressionParser();
        Expression expression = parser.parseExpression(message, new TemplateParserContext());
        StandardEvaluationContext context = new StandardEvaluationContext();
        context.setVariable("data", data);

        System.out.println(expression.getValue(context,String.class));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接