Search code examples
javaspringspring-el

SpEL templates mixing expressions and literals


how can i parse a "complex" template-like SpEL expression that mixes literal text and actual #{SpEL expressions}? for example:

the dog says #{dog.getSound()}

Apache Camel supports this template-like capability in its expression languages (including SpEL), but i haven't been able to root out how to accomplish this directly with vanilla SpEL.


Solution

  • as described in the user guide, evaluate the Expression in a TemplateParserContext:

    String randomPhrase = 
        parser.parseExpression("random number is #{T(java.lang.Math).random()}", 
                          new TemplateParserContext()).getValue(String.class);
    
    // evaluates to "random number is 0.7038186818312008"