00:00

Spring Expression Language (SpEL)

Last updated:

The Spring Expression Language (SpEL) is a small expression language that Spring evaluates at runtime. You meet it whenever an annotation contains #{...} or a short formula: a computed @Value, a cache key such as #sku + ':' + #currency, or a security rule like hasRole('ADMIN'). SpEL can read properties, call methods, reference other beans, filter collections and do arithmetic and logic, which makes configuration and annotations far more expressive.

This tutorial explains the difference between ${...} and #{...}, walks through the SpEL syntax with examples from a shop, shows where Spring uses SpEL in annotations, and covers evaluating expressions in your own code safely, including why user-supplied expressions must never run with full power.

1. What Is the Spring Expression Language?

An expression language evaluates short formulas written as text, such as price * quantity > 100. SpEL is Spring's own, part of the spring-expression module that every Spring application includes. Expressions are evaluated against a context: a root object whose properties you can read, variables, and, inside the container, the beans.

Analogy: A spreadsheet formula such as =B2*C2 is written as text, refers to cells and is recalculated when needed. SpEL expressions are formulas for your Spring configuration and annotations, referring to properties, beans and method arguments instead of cells.

2. ${...} vs #{...}

SyntaxWhat it isEvaluated byExample
${...}Property placeholder: a simple lookup with an optional defaultThe Environment${shop.currency:EUR}
#{...}SpEL expression: logic, method calls, bean referencesThe SpEL engine#{2 * 60 * 1000}

They can be combined: placeholders are resolved first, then the expression is evaluated. In #{'${shop.allowed-currencies}'.split(',')}, the property text is inserted into a SpEL string literal, which is then split into an array.

3. SpEL Syntax by Example

FeatureExampleResult
Literals'KB-100', 42, 79.99, true, nullString, int, double, boolean, null
Arithmeticprice * quantity, total - discount, 10 % 3Numbers
Relationaltotal > 100, tier == 'GOLD' (also gt, eq, ...)boolean
Logicala and b, a or b, not a (also &&, ||, !)boolean
Ternarystock > 0 ? 'IN_STOCK' : 'SOLD_OUT'One of two values
Elvisnickname ?: 'Guest'Value, or the default if it is null
Safe navigationcustomer?.address?.citynull instead of an exception if a step is null
Properties and methodsname.toUpperCase(), items.size()Calls getters and methods
Type referenceT(java.lang.Math).min(5, stock)Calls a static method
Bean reference@pricingRules.defaultDiscount()Uses a bean from the container
Variables#sku, #root, #thisNamed values, the root object, the current element
Selectionitems.?[price > 50]Elements matching a condition
Projectionitems.![sku]A list of one property from each element
Inline list and map{'EUR','INR'}, {tier:'GOLD', rate:0.1}Lists and maps

4. SpEL in @Value

ShopSettings.java
package com.javabytechie.shop.config;

import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ShopSettings {

    private final long cacheTtlMillis;
    private final List<String> currencies;
    private final String region;
    private final boolean freeShipping;

    public ShopSettings(
            @Value("#{${shop.cache-ttl-minutes:5} * 60 * 1000}") long cacheTtlMillis,
            @Value("#{'${shop.allowed-currencies:EUR,INR}'.split(',')}") List<String> currencies,
            @Value("#{systemEnvironment['SHOP_REGION'] ?: 'EU'}") String region,
            @Value("#{${shop.free-shipping-threshold:50} < 100}") boolean freeShipping) {
        this.cacheTtlMillis = cacheTtlMillis;
        this.currencies = currencies;
        this.region = region;
        this.freeShipping = freeShipping;
    }

    @Override
    public String toString() {
        return "ShopSettings[ttl=" + cacheTtlMillis + "ms, currencies=" + currencies
                + ", region=" + region + ", freeShippingBelow100=" + freeShipping + "]";
    }
}
Console (with default property values and no SHOP_REGION variable)
ShopSettings[ttl=300000ms, currencies=[EUR, INR], region=EU, freeShippingBelow100=true]

Inside the container, systemProperties and systemEnvironment are predefined variables. For anything beyond a small calculation, prefer a @ConfigurationProperties record: it is type-safe, validated and easier to test than an expression inside an annotation.

5. Where Spring Uses SpEL in Annotations

AnnotationExampleAvailable in the expression
@Cacheable, @CacheEvictkey = "#sku + ':' + #currency", condition = "#currency != null", unless = "#result == null"Method arguments by name, #result
@PreAuthorize, @PostAuthorize"hasRole('ADMIN') or #customerId == authentication.name"Security functions, arguments, returnObject
@EventListenercondition = "#event.total > 1000"The event
@ConditionalOnExpression (Spring Boot)"${shop.features.recommendations:true} and ${shop.features.beta:false}"Properties and beans
@KafkaListenertopics = "#{'${shop.topics}'.split(',')}"Properties and beans
@Scheduledcron = "${shop.report.cron}" (placeholder only)Properties

See caching and @PreAuthorize for more examples of these annotations.

6. Evaluating Expressions in Code

The SpEL API has three parts: an ExpressionParser (usually SpelExpressionParser) turns text into an Expression, and an EvaluationContext decides what the expression may access.

SpEL API basics
ExpressionParser parser = new SpelExpressionParser();
Expression expression = parser.parseExpression("price * quantity");   // parse once, reuse
EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding()
        .withRootObject(new OrderLine(new BigDecimal("24.99"), 3))
        .build();
BigDecimal total = expression.getValue(context, BigDecimal.class);    // 74.97
ContextCan doUse for
SimpleEvaluationContextRead (optionally write) properties of the root object, variables, operators. No type references, constructors or bean references.Expressions that come from configuration or users
StandardEvaluationContextEverything: T(...), new, any method, bean referencesTrusted expressions written by developers

Parsing is relatively expensive; parse an expression once and keep the Expression object, which is thread-safe to evaluate.

7. A Complete Example: Admin-Defined Discount Rules

Shop administrators define discount rules as short expressions, such as total > 100 and customerTier == 'GOLD', stored in the database. The application evaluates them for each order with a restricted context.

7.1 The Data the Rules May See

OrderFacts.java
package com.javabytechie.shop.discount;

import java.math.BigDecimal;

public class OrderFacts {

    private final BigDecimal total;
    private final String customerTier;
    private final int itemCount;

    public OrderFacts(BigDecimal total, String customerTier, int itemCount) {
        this.total = total;
        this.customerTier = customerTier;
        this.itemCount = itemCount;
    }

    public BigDecimal getTotal() {
        return total;
    }

    public String getCustomerTier() {
        return customerTier;
    }

    public int getItemCount() {
        return itemCount;
    }
}

The class exposes only what rules need, through getters, which the read-only data binding accessor uses.

7.2 The Rule Evaluator

DiscountRuleEvaluator.java
package com.javabytechie.shop.discount;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionException;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.SimpleEvaluationContext;
import org.springframework.stereotype.Service;

@Service
public class DiscountRuleEvaluator {

    private static final Logger log = LoggerFactory.getLogger(DiscountRuleEvaluator.class);
    private final ExpressionParser parser = new SpelExpressionParser();
    private final Map<String, Expression> cache = new ConcurrentHashMap<>();

    public record DiscountRule(String name, String condition, BigDecimal percent) {
    }

    public BigDecimal bestDiscount(OrderFacts order, List<DiscountRule> rules) {
        EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding()
                .withRootObject(order)
                .build();
        BigDecimal best = BigDecimal.ZERO;
        for (DiscountRule rule : rules) {
            if (matches(rule, context) && rule.percent().compareTo(best) > 0) {
                best = rule.percent();
            }
        }
        return best;
    }

    private boolean matches(DiscountRule rule, EvaluationContext context) {
        try {
            Expression expression = cache.computeIfAbsent(rule.condition(), parser::parseExpression);
            return Boolean.TRUE.equals(expression.getValue(context, Boolean.class));
        } catch (ExpressionException ex) {   // parse and evaluation errors
            log.warn("Discount rule '{}' is invalid and was skipped: {}", rule.name(), ex.getMessage());
            return false;
        }
    }
}

7.3 Run It

DiscountDemo.java
package com.javabytechie.shop.discount;

import com.javabytechie.shop.discount.DiscountRuleEvaluator.DiscountRule;
import java.math.BigDecimal;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration(proxyBeanMethods = false)
class DiscountDemo {

    private static final Logger log = LoggerFactory.getLogger(DiscountDemo.class);

    @Bean
    ApplicationRunner discountRunner(DiscountRuleEvaluator evaluator) {
        List<DiscountRule> rules = List.of(
                new DiscountRule("gold-over-100", "total > 100 and customerTier == 'GOLD'", new BigDecimal("10")),
                new DiscountRule("bulk", "itemCount >= 5", new BigDecimal("5")),
                new DiscountRule("hacker", "T(java.lang.Runtime).getRuntime().exec('rm -rf /')", new BigDecimal("99")));
        return args -> {
            log.info("Gold customer, 120 total, 2 items: {}% off",
                    evaluator.bestDiscount(new OrderFacts(new BigDecimal("120"), "GOLD", 2), rules));
            log.info("Silver customer, 80 total, 6 items: {}% off",
                    evaluator.bestDiscount(new OrderFacts(new BigDecimal("80"), "SILVER", 6), rules));
        };
    }
}
Console
Discount rule 'hacker' is invalid and was skipped: EL1005E: Type cannot be found 'java.lang.Runtime'
Gold customer, 120 total, 2 items: 10% off
Discount rule 'hacker' is invalid and was skipped: EL1005E: Type cannot be found 'java.lang.Runtime'
Silver customer, 80 total, 6 items: 5% off

The malicious rule was rejected, because SimpleEvaluationContext does not resolve type references. The exact error text may differ between versions; what matters is that evaluation fails instead of running code.

8. Security: Never Evaluate Untrusted Expressions with Full Power

With StandardEvaluationContext, an expression can create objects, call static methods and run operating system commands. If any part of an expression comes from a user, a request parameter or an editable database row, that is a SpEL injection vulnerability that can lead to remote code execution.

  • Use SimpleEvaluationContext for anything that is not written by developers.
  • Never concatenate user input into an expression string, for example into a @Cacheable key template built at runtime.
  • Expose a dedicated, read-only root object such as OrderFacts, not your entities or services.
  • Validate rules when they are saved, by parsing them and evaluating against sample data.

9. Testing Expressions

DiscountRuleEvaluatorTest.java
package com.javabytechie.shop.discount;

import static org.assertj.core.api.Assertions.assertThat;

import com.javabytechie.shop.discount.DiscountRuleEvaluator.DiscountRule;
import java.math.BigDecimal;
import java.util.List;
import org.junit.jupiter.api.Test;

class DiscountRuleEvaluatorTest {

    private final DiscountRuleEvaluator evaluator = new DiscountRuleEvaluator();
    private final DiscountRule gold = new DiscountRule("gold", "total > 100 and customerTier == 'GOLD'", BigDecimal.TEN);

    @Test
    void appliesARuleOnlyWhenItsConditionMatches() {
        OrderFacts small = new OrderFacts(new BigDecimal("90"), "GOLD", 1);
        OrderFacts large = new OrderFacts(new BigDecimal("150"), "GOLD", 1);

        assertThat(evaluator.bestDiscount(small, List.of(gold))).isEqualByComparingTo("0");
        assertThat(evaluator.bestDiscount(large, List.of(gold))).isEqualByComparingTo("10");
    }

    @Test
    void ignoresRulesThatTryToReachJavaTypes() {
        DiscountRule attack = new DiscountRule("attack", "T(java.lang.System).exit(1) == null", new BigDecimal("50"));

        assertThat(evaluator.bestDiscount(new OrderFacts(BigDecimal.ONE, "GOLD", 1), List.of(attack)))
                .isEqualByComparingTo("0");
    }
}

10. When to Use SpEL and When to Avoid It

Good useBetter alternative
Cache keys, cache conditions and security rules in annotationsLong expressions: move logic into a bean method and call it with @bean.method(...)
Small calculations or defaults in @ValueGroups of settings: @ConfigurationProperties
Simple, admin-defined rules with a restricted contextComplex business rules: plain Java or a dedicated rules engine
Conditional beans with @ConditionalOnExpressionSingle property checks: @ConditionalOnProperty

11. Best Practices

  • Keep expressions short; move anything complex into a bean method.
  • Use ${...} for simple property lookups and #{...} only when you need logic.
  • Parse once and reuse Expression objects.
  • Use SimpleEvaluationContext for untrusted input, with a dedicated root object.
  • Compile with -parameters so annotations such as @Cacheable can refer to arguments by name (Spring Boot's build plugins do this).
  • Test expressions, especially rules stored outside the code.

12. Summary

The Spring Expression Language evaluates small formulas at runtime: arithmetic, logic, method calls, bean references and collection filtering. Use ${...} for property lookups and #{...} when you need logic, in @Value, cache keys, security rules, event conditions and conditional beans. In your own code, parse with SpelExpressionParser, reuse the parsed Expression, and choose the context carefully: StandardEvaluationContext for trusted expressions, SimpleEvaluationContext for anything a user can influence, so that a rule can read order data but can never run code.

13. References