Spring Framework Tutorial 0/19 lessons ~6 min read Lesson 9

    Spring Expression Language (SpEL)

    SpEL is a small expression language built into Spring.

    Course progress0%
    Focus
    11 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    SpEL is a small expression language built into Spring. It evaluates strings such as #{pricingRules.discountFor('GOLD')} at runtime against beans, properties, and objects. You meet it in @Value, @PreAuthorize, @Cacheable(condition = …), @EventListener(condition = …), and Spring Integration routing.

    SpEL is powerful enough to call methods and construct types, which is exactly why it must never evaluate untrusted input with the full evaluation context.

    Purpose of this lesson

    You will use SpEL in @Value, evaluate expressions programmatically, filter and project collections, and choose the safe SimpleEvaluationContext when input is not fully trusted.

    Understanding the topic

    Two syntaxes that look alike but do different things:

    • ${checkout.region:eu-west-1} — a property placeholder, resolved from the Environment with an optional default after the colon. No expression logic.
    • #{...} — a SpEL expression, evaluated at runtime. It can reference beans by name, call methods, do arithmetic, and use the Elvis operator ?:.
    • They compose: #{${checkout.max-items:20} * 2} resolves the placeholder first, then evaluates the arithmetic.
    • Collection operators: selection .?[cond], first match .^[cond], last match .$[cond], projection .![expr].
    • Safe navigation ?. returns null instead of throwing when the left side is null.
    • T(java.lang.Math) references a type; @beanName references a bean in an evaluation context with a bean resolver.

    Syntax reference

    SpEL inside @Value — checkout.properties contains checkout.region=ap-south-1 and checkout.max-items=25:

    java
    public class PricingRules {
    private final Map<String, Integer> discounts = Map.of("GOLD", 15, "SILVER", 5);
    public int discountFor(String tier) { return discounts.getOrDefault(tier, 0); }
    }
    @Component
    public class CheckoutSettings {
    @Value("${checkout.region:eu-west-1}")
    String region;
    @Value("#{${checkout.max-items:20} * 2}")
    int maxItemsDuringSale;
    @Value("#{pricingRules.discountFor('GOLD')}")
    int goldDiscount;
    @Value("#{systemProperties['checkout.mode'] ?: 'live'}")
    String mode;
    }
    @Configuration
    @PropertySource("classpath:checkout.properties")
    class AppConfig {
    @Bean PricingRules pricingRules() { return new PricingRules(); }
    @Bean CheckoutSettings checkoutSettings() { return new CheckoutSettings(); }
    }
    public static void main(String[] args) {
    try (var ctx = new AnnotationConfigApplicationContext(AppConfig.class)) {
    CheckoutSettings s = ctx.getBean(CheckoutSettings.class);
    System.out.println("region=" + s.region);
    System.out.println("maxItemsDuringSale=" + s.maxItemsDuringSale);
    System.out.println("goldDiscount=" + s.goldDiscount);
    System.out.println("mode=" + s.mode);
    }
    }

    Output

    region=ap-south-1
    maxItemsDuringSale=50
    goldDiscount=15
    mode=live

    Run it again with -Dcheckout.mode=dry-run and the last line becomes mode=dry-run: the Elvis operator only falls back to 'live' when the system property is missing.

    Informative example

    Evaluating expressions programmatically with SpelExpressionParser (Order is a plain class with getId(), getTotalCents(), and getTier()):

    java
    ExpressionParser parser = new SpelExpressionParser();
    System.out.println(parser.parseExpression("'Hello, ' + 'SpEL'").getValue(String.class));
    System.out.println(parser.parseExpression("6 * 7").getValue(Integer.class));
    Order order = new Order("o-1001", 12999, "GOLD");
    EvaluationContext readOnly = SimpleEvaluationContext.forReadOnlyDataBinding().build();
    String shipping = parser
    .parseExpression("totalCents >= 10000 or tier == 'GOLD' ? 'FREE' : 'STANDARD'")
    .getValue(readOnly, order, String.class);
    System.out.println("shipping=" + shipping);
    StandardEvaluationContext ctx = new StandardEvaluationContext();
    ctx.setVariable("orders", List.of(
    new Order("o-1001", 12999, "GOLD"),
    new Order("o-1002", 2500, "BASIC"),
    new Order("o-1003", 7800, "SILVER")));
    System.out.println("big orders=" + parser.parseExpression("#orders.?[totalCents > 5000].![id]").getValue(ctx));
    System.out.println("first basic=" + parser.parseExpression("#orders.^[tier == 'BASIC']?.id").getValue(ctx));
    try {
    parser.parseExpression("T(java.lang.Runtime).getRuntime().availableProcessors()")
    .getValue(readOnly, order);
    } catch (Exception ex) {
    System.out.println("blocked: " + ex.getClass().getSimpleName());
    }

    Output

    Hello, SpEL
    42
    shipping=FREE
    big orders=[o-1001, o-1003]
    first basic=o-1002
    blocked: SpelEvaluationException

    The last expression tries to reach java.lang.Runtime. SimpleEvaluationContext does not support type references, so evaluation fails instead of touching the JVM.

    Security implications

    SpEL injection is a real vulnerability class: if user input reaches parser.parseExpression(input).getValue(new StandardEvaluationContext()), an attacker can write T(java.lang.Runtime).getRuntime().exec(...) and run commands on your server.

    • Never build expression strings from request parameters, headers, or database values edited by users.
    • When you must evaluate semi-trusted expressions (for example admin-defined rules), use SimpleEvaluationContext.forReadOnlyDataBinding() — no type references, constructors, or bean references.
    • Annotation expressions (@PreAuthorize, @Value) are written by developers at compile time, so they are safe — keep it that way.

    Best practices

    • Use ${…} for configuration values and #{…} only when you need logic.
    • Keep expressions short; move anything longer than one line into a bean method and call it from SpEL.
    • Prefer typed configuration (@ConfigurationProperties in Boot, or a config bean) over many scattered @Value expressions.
    • Cache parsed Expression objects if you evaluate the same rule many times — parsing is the expensive part.

    Common mistakes

    • Writing #{checkout.region} when you meant ${checkout.region} — SpEL looks for a bean named checkout and fails.
    • Using #event or #user in annotation conditions when the method parameter has a different name — SpEL resolves #name against parameter names (compile with -parameters), or use #a0/#p0.
    • Evaluating user-supplied expressions with StandardEvaluationContext.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    2 questions
    1BeginnerQuestionWhat is the difference between ${...} and #{...} in Spring?+

    Answer

    ${...} is a property placeholder resolved from the Environment (property files, system properties, environment variables). #{...} is a SpEL expression evaluated at runtime and can call methods, reference beans, and do arithmetic. They can be combined, with placeholders resolved first.
    2IntermediateQuestionWhy is SpEL a security risk and how do you mitigate it?+

    Answer

    StandardEvaluationContext allows type references and method calls, so evaluating attacker-controlled strings can execute arbitrary code. Never evaluate untrusted input; when you must evaluate semi-trusted expressions, use SimpleEvaluationContext, which blocks type references, constructors, and bean references.

    Follow-up

    Where in Spring does SpEL appear by default? (@Value, @PreAuthorize, @Cacheable, @EventListener conditions.)

    Hands-on exercise

    Hands-on: add a shipping.free-threshold-cents=10000 property and inject #{${shipping.free-threshold-cents} / 100} as an int named freeThresholdDollars. Print it (expected 100). Then write a programmatic rule #orders.?[tier != 'BASIC'].size() against the three orders above and confirm it prints 2.

    Summary

    SpEL adds runtime logic to Spring configuration and annotations. Use placeholders for plain values, SpEL for small pieces of logic, and the restricted evaluation context whenever input is not fully trusted.

    Ready to mark this lesson complete?Track your journey across the entire course.