Spring Expression Language (SpEL) is a feature in the Spring Framework used to evaluate expressions and manipulate objects at runtime. It helps in dynamically configuring beans, accessing properties, and invoking methods within Spring applications.
- Supports querying and modifying object values at runtime
- Used for dynamic bean configuration and value injection
- Provides operators (arithmetic, logical, relational) for expression evaluation
Syntax:
- #{}: Used for evaluating expressions dynamically in Spring bean definitions.
- ${}: Used for property placeholders (externalized configuration).
Key Features:
- Property Access: Access object properties using a simple syntax.
- Method Invocation: Call methods on beans or objects dynamically.
- Arithmetic Operations: Perform calculations like addition, subtraction, multiplication, and division.
- Logical and Relational Operators: Evaluate boolean expressions using ==, >, <, &&, ||.
- Collection Support: Access arrays, lists, maps, and sets.
- Bean References: Reference Spring beans by their ID.
- Ternary Operator: Use ? : for conditional expressions.
- Regular Expression Matching: Supports matches for pattern matching.
Basic Usage in Spring XML
<bean id="exampleBean" class="com.example.Person">
<property name="age" value="#{30 + 5}" />
<property name="name" value="#{'John Doe'}" />
</bean>
Explanation:
- #{30 + 5} evaluates to 35 and sets the age property.
- #{'John Doe'} sets the name property.
Using SpEL with Annotations
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Employee {
@Value("#{10 * 2}") // Arithmetic operation
private int salary;
@Value("#{'John'.toUpperCase()}") // Method invocation
private String name;
public int getSalary() { return salary; }
public String getName() { return name; }
}
Explanation:
- SpEL evaluates 10 * 2 to 20 and assigns it to salary.
- The toUpperCase() method converts "John" to "JOHN".
Accessing Beans in SpEL
@Component("myBean")
public class MyBean {
private String value = "Spring SpEL";
public String getValue() { return value; }
}
@Component
public class Demo {
@Value("#{myBean.value}") // Access property of another bean
private String val;
}
Explanation:
- #{myBean.value} references the value property of the bean with ID myBean.
SpEL Operators
| Operator | Description | Example |
|---|---|---|
+ | Addition / Concatenation | #{2 + 3} → 5 |
- | Subtraction | #{10 - 4} → 6 |
* | Multiplication | #{5 * 2} → 10 |
/ | Division | #{10 / 2} → 5 |
% | Modulus | #{10 % 3} → 1 |
== | Equals | #{5 == 5} → true |
!= | Not equals | #{5 != 2} → true |
> | Greater than | #{10 > 5} → true |
| < | Less than | #{3 < 7} → true |
| and / && | Logical AND | #{true and false} → false |
| `or / | ` | |
| ! | Logical NOT | #{!true} → false |
?: | Ternary | #{1 > 0 ? 'Yes' : 'No'} → "Yes" |
Working with Collections
@Value("#{{1, 2, 3, 4}.?[#this > 2]}") // Selection
private List<Integer> filteredList;
@Value("#{{'a':'A', 'b':'B'}}") // Map initialization
private Map<String, String> map;
- Projection (!): Transforms each element.
- Selection (.?): Filters elements based on a condition.
Programmatic Evaluation of SpEL
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.Expression;
public class SpELProgrammatic {
public static void main(String[] args) {
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("'Hello World'.concat('!!!')");
String message = exp.getValue(String.class);
System.out.println(message);
}
}
Output:
Hello World!!!
Advantages of Using SpEL
- Enables dynamic bean configuration without hardcoding values.
- Simplifies access to bean properties and methods in a declarative manner.
- Supports complex expressions, including collections, maps, ternary operations, and regular expressions.
- Integrates with Spring annotations and XML configuration seamlessly.
- Allows runtime evaluation for programmatic scenarios.