Spring Expression Language (SpEL)

What SpEL is and where Spring uses it: syntax (literals, properties, methods, operators, collection selection and projection, safe navigation, Elvis), bean references, @Value with ${} vs #{}, SpEL in security, caching and scheduling annotations, evaluating expressions programmatically, compilation, and security risks of user-supplied expressions.

On this page

Simple definition#

SpEL (Spring Expression Language) is a small expression language that Spring evaluates at runtime against objects, beans and context. It powers dynamic values in annotations such as @Value("#{…}"), @PreAuthorize("…"), @Cacheable(key = "…") and @EventListener(condition = "…").

The problem#

Annotations are static, but many decisions are dynamic: “allow if the user owns this order”, “cache by customer ID”, “listen only to large orders”. SpEL lets those rules be written declaratively, next to the code they affect.

${…} vs #{…}#

SyntaxWhat it isExample
${…}Property placeholder, resolved from the Environment (properties, env vars)@Value("${shop.page-size:20}")
#{…}SpEL expression, evaluated at runtime@Value("#{T(java.time.Duration).ofSeconds(${shop.timeout-seconds})}")

You can nest a placeholder inside SpEL, as shown. For configuration, prefer type-safe @ConfigurationProperties over scattered @Values.

Syntax tour#

FeatureExampleResult
Literals'text', 42, true, null—
Properties and methodsorder.customer.name, name.toUpperCase()Navigation and calls
Operatorstotal > 100 and status == 'PAID', + - * / %, matches (regex)Boolean and arithmetic
Ternaryvip ? 0.1 : 0.0—
Elvisnickname ?: 'guest'Default if null
Safe navigationcustomer?.address?.citynull instead of an NPE
Types and staticsT(java.lang.Math).max(a, b)Static access
Bean references@pricingService.discountFor(#customer)Call a bean
Variables#order, #root, #thisContext variables and method arguments
Collection selectionorders.?[total > 100]Filter (^[…] first match, $[…] last)
Collection projectionorders.![id]Map to IDs
Inline lists and maps{1, 2, 3}, {currency: 'EUR'}—

Where Spring uses SpEL#

// Method security: argument and return-value checks
@PreAuthorize("hasRole('ADMIN') or #customerId == authentication.name")
Orders listOrders(String customerId) { ... }

@PostAuthorize("returnObject.ownerId == authentication.name")
Order getOrder(long id) { ... }

// Caching: computed keys and conditions
@Cacheable(cacheNames = "prices", key = "#sku + ':' + #currency", unless = "#result == null")
Price price(String sku, String currency) { ... }

// Events: conditional listeners
@EventListener(condition = "#event.total > 1000")
void onLargeOrder(OrderPlaced event) { ... }

// Scheduling with a property
@Scheduled(cron = "${jobs.reconcile.cron}")
void reconcile() { ... }

Spring Data also supports SpEL in @Query (:#{#entityName}), and Spring Integration and Spring Cloud Stream use SpEL for routing and headers.

Evaluating expressions in code#

ExpressionParser parser = new SpelExpressionParser();
Expression rule = parser.parseExpression("total > 500 and customer.country == 'IN'");

var context = SimpleEvaluationContext.forReadOnlyDataBinding().build();   // restricted
boolean flagged = rule.getValue(context, order, Boolean.class);
  • Parse once and reuse the Expression objects (parsing is the costly part).
  • SimpleEvaluationContext is restricted: no type references, constructors or bean references. StandardEvaluationContext allows everything.
  • Compilation: SpelCompilerMode.IMMEDIATE or MIXED compiles hot expressions to bytecode for speed.

Security warning: SpEL injection#

When not to use SpEL#

  • Complex business logic: put it in a Java method and call it (@authz.canEdit(#order)). That keeps it testable and refactorable.
  • Configuration values: use @ConfigurationProperties.

Common mistakes#

Quick check#

${…} vs #{…}? ${…} is a property placeholder resolved from the Environment. #{…} is a SpEL expression evaluated at runtime.

What does customer?.address?.city do? Safe navigation: it returns null instead of throwing NullPointerException if any part is null.

Name three annotations that accept SpEL. @PreAuthorize and @PostAuthorize, @Cacheable (key, condition, unless), @EventListener(condition) and @Value("#{…}").

Why is evaluating user input with SpEL dangerous? StandardEvaluationContext allows type references and method calls, which enables arbitrary code execution.

How do you call a bean in an expression? With @beanName.method(...), for example @authz.canEdit(#order).

Summary#

  • SpEL evaluates runtime expressions; ${} is just property lookup.
  • Spring uses it in security, caching, events, scheduling and data annotations.
  • Keep expressions short; delegate logic to beans; never evaluate untrusted input.

References#