Spring Expression Language (SpEL)
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.
=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 #{...}
| Syntax | What it is | Evaluated by | Example |
|---|---|---|---|
${...} | Property placeholder: a simple lookup with an optional default | The Environment | ${shop.currency:EUR} |
#{...} | SpEL expression: logic, method calls, bean references | The 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
| Feature | Example | Result |
|---|---|---|
| Literals | 'KB-100', 42, 79.99, true, null | String, int, double, boolean, null |
| Arithmetic | price * quantity, total - discount, 10 % 3 | Numbers |
| Relational | total > 100, tier == 'GOLD' (also gt, eq, ...) | boolean |
| Logical | a and b, a or b, not a (also &&, ||, !) | boolean |
| Ternary | stock > 0 ? 'IN_STOCK' : 'SOLD_OUT' | One of two values |
| Elvis | nickname ?: 'Guest' | Value, or the default if it is null |
| Safe navigation | customer?.address?.city | null instead of an exception if a step is null |
| Properties and methods | name.toUpperCase(), items.size() | Calls getters and methods |
| Type reference | T(java.lang.Math).min(5, stock) | Calls a static method |
| Bean reference | @pricingRules.defaultDiscount() | Uses a bean from the container |
| Variables | #sku, #root, #this | Named values, the root object, the current element |
| Selection | items.?[price > 50] | Elements matching a condition |
| Projection | items.![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
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 + "]";
}
}
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
| Annotation | Example | Available in the expression |
|---|---|---|
@Cacheable, @CacheEvict | key = "#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 |
@EventListener | condition = "#event.total > 1000" | The event |
@ConditionalOnExpression (Spring Boot) | "${shop.features.recommendations:true} and ${shop.features.beta:false}" | Properties and beans |
@KafkaListener | topics = "#{'${shop.topics}'.split(',')}" | Properties and beans |
@Scheduled | cron = "${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.
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
| Context | Can do | Use for |
|---|---|---|
SimpleEvaluationContext | Read (optionally write) properties of the root object, variables, operators. No type references, constructors or bean references. | Expressions that come from configuration or users |
StandardEvaluationContext | Everything: T(...), new, any method, bean references | Trusted 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
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
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
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));
};
}
}
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
SimpleEvaluationContextfor anything that is not written by developers. - Never concatenate user input into an expression string, for example into a
@Cacheablekey 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
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 use | Better alternative |
|---|---|
| Cache keys, cache conditions and security rules in annotations | Long expressions: move logic into a bean method and call it with @bean.method(...) |
Small calculations or defaults in @Value | Groups of settings: @ConfigurationProperties |
| Simple, admin-defined rules with a restricted context | Complex business rules: plain Java or a dedicated rules engine |
Conditional beans with @ConditionalOnExpression | Single 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
Expressionobjects. - Use
SimpleEvaluationContextfor untrusted input, with a dedicated root object. - Compile with
-parametersso annotations such as@Cacheablecan 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
Spring Expression Language (SpEL) Interview Questions and Answers
Common interview questions on Spring Expression Language (SpEL), from basic to scenario-based, with short answers you can explain in your own words.
Q. What is the difference between ${...} and #{...} in Spring?
Answer: ${...} is a property placeholder resolved against the Environment, with an optional default after a colon. #{...} is a SpEL expression that can compute values, call methods and reference beans. They can be combined: placeholders are resolved first, so #{'${shop.currencies}'.split(',')} splits a property value into an array.
Q. What are the Elvis operator and safe navigation in SpEL?
Answer: The Elvis operator a ?: b returns a unless it is null (or an empty string), otherwise b, which is handy for defaults. Safe navigation a?.b returns null instead of throwing when a is null, so customer?.address?.city works even if the customer has no address.
Q. How can a @Cacheable key refer to method arguments by name?
Answer: Spring evaluates the key as SpEL with the method arguments available as variables, for example key = "#sku + ':' + #currency". Names are taken from the compiled parameter names, which requires the -parameters compiler flag that Spring Boot's build plugins enable; otherwise you can use #p0 or #a0 for positions. #result is available in unless conditions.
Q. What is the difference between StandardEvaluationContext and SimpleEvaluationContext?
Answer: StandardEvaluationContext supports the full language: type references with T(...), constructors, any method, bean references. SimpleEvaluationContext supports a restricted subset, essentially property access on a root object, variables and operators, and is meant for expressions that are not fully trusted. Use the simple context whenever input comes from users or configuration others can edit.
Q. A reporting feature builds a SpEL expression from a "sort field" request parameter. Why is that dangerous, and how do you fix it?
Answer: Concatenating request data into an expression evaluated with a standard context lets an attacker inject T(java.lang.Runtime).getRuntime().exec(...), which is remote code execution. Do not build expressions from input at all: map the allowed sort fields to fixed values or a Comparator in Java. If expressions are truly needed, evaluate them with SimpleEvaluationContext against a dedicated read-only object.