Skip to content

SpEL Parser and Evaluation Context

The SpEL Parser and Evaluation Context are the core components used to programmatically evaluate Spring Expression Language (SpEL) strings at runtime.^[600-developer__spring__spring-spel.md] While SpEL is commonly used within Spring configuration files or annotations via the #{ ... } syntax, it can also be invoked directly in Java code using dedicated classes for parsing and context management.^[600-developer__spring__spring-spel.md]

Components

ExpressionParser

The ExpressionParser is responsible for parsing the raw expression string into a prepared form that can be evaluated.^[600-developer__spring__spring-spel.md] The standard implementation provided by Spring is SpelExpressionParser.^[600-developer__spring__spring-spel.md]

EvaluationContext

The EvaluationContext serves as the configuration container for the evaluation process.^[600-developer__spring__spring-spel.md] It is used to define variables, register functions, and set the root object against which the expression is executed.^[600-developer__spring__spring-spel.md] The standard implementation is StandardEvaluationContext.^[600-developer__spring__spring-spel.md]

ParserContext

When parsing an expression, a ParserContext can be supplied to define the specific syntax rules, such as the prefix and suffix delimiters that identify the expression within a larger string (e.g., #{ ... }).^[600-developer__spring__spring-spel.md]

Evaluation Workflow

The process of evaluating an expression programmatically generally follows three steps:^[600-developer__spring__spring-spel.md]

  1. Initialization: Create an instance of the parser (new SpelExpressionParser()) and an empty context (new StandardEvaluationContext()).^[600-developer__spring__spring-spel.md]
  2. Parsing: Call the parseExpression method on the parser, passing the expression string and optionally a ParserContext if the expression is embedded in a template.^[600-developer__spring__spring-spel.md]
  3. Evaluation: Execute the getValue method on the resulting Expression object, passing the EvaluationContext to retrieve the final result.^[600-developer__spring__spring-spel.md]

Examples

Basic Programmatic Usage

The following pattern demonstrates how to instantiate the parser and context to execute an expression:^[600-developer__spring__spring-spel.md]

ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression(content, ParserContext.TEMPLATE_EXPRESSION);
EvaluationContext context = new StandardEvaluationContext();
return exp.getValue(context);

Root Variables and Method Calls

The EvaluationContext allows specific variables or objects to be set as the "root" of the expression.^[600-developer__spring__spring-spel.md] This enables expressions to invoke methods or access properties on the provided object.^[600-developer__spring__spring-spel.md]

Sources

^[600-developer__spring__spring-spel.md]