Configuration values and bean wiring often require dynamic expressions — accessing system properties, evaluating conditions, performing string operations, or calling methods. Static property files (@Value("${key}")) can only do basic key lookups; developers need runtime expression evaluation within the Spring container.
SpEL (Spring Expression Language) is a powerful expression language that supports querying and manipulating objects at runtime. It can be used in XML and annotation-based configurations, providing dynamic value resolution, method invocation, collection manipulation, and boolean evaluation.
- Syntax: Expressions start with
#{and end with}— e.g.,#{systemProperties['user.dir']} - Property access:
#{beanName.property}accesses any Spring bean’s property - Method invocation:
#{beanName.method(args)}calls methods on beans - Operators: Arithmetic (
+,-,*,/), relational (==,lt,gt), logical (and,or,not) - Collection selection:
#{users.?[age > 25]}filters collections;.^first match,.$last match - Collection projection:
#{users.![name]}extracts specific property from each element - Safe navigation:
#{bean?.property}— returns null if bean is null instead of NPE - Ternary:
#{bean.score > 50 ? 'Pass' : 'Fail'}
- Dynamic evaluation: Expressions are evaluated at runtime, not compile time
- Bean access: Directly reference Spring beans by name (
#{myBean.count}) - Null-safe:
?.operator prevents NullPointerException in navigation chains - Collection operators: Selection (
?[]), projection (![]), sorting according to a property - Type operators:
T(java.lang.Math).PIreferences static types and methods - Integration: Works with
@Value, XML<property>, security annotations, and more
- Built from: Spring Framework — SpEL is a Spring Core module
- Built from: Spring IoC Container — SpEL evaluates within the container’s context
- Related: Spring Annotations — @Value with SpEL provides dynamic property injection
- Contrasts with: EJB Query Language (EJB-QL) — EJB-QL queries entities; SpEL queries beans and system properties
- Related: Java Operators — SpEL operators extend Java’s with collection-safe operations
- Syntax confusion:
#{}(SpEL evaluation) vs${}(property placeholder) — they can be nested:#{${property}} - Performance: Complex SpEL expressions are evaluated on every access — avoid in hot paths
- Method invocation: Only public methods on beans can be called; private/static methods require T() type operator
- Security: SpEL can call any bean method and access any property — never use user-provided input in SpEL expressions (security risk)