The Spring Expression Language (SpEL) is a powerful expression language that supports querying and manipulating an object graph at runtime. The language syntax is similar to Unified EL but offers additional features, most notably method invocation and basic string templating functionality.
4.1. Evaluation
This section introduces the simple use of SpEL interfaces and its expression language.
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("'Hello World'");
String message = (String) exp.getValue();
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("'Hello World'.concat('!')");
String message = (String) exp.getValue();
The more common usage of SpEL is to provide an expression string that is evaluated against a specific object instance.
// The constructor arguments are name, birthday, and nationality.
Inventor tesla = new Inventor("Nikola Tesla", "China");
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("name");
String name = (String) exp.getValue(tesla);
// name == "Nikola Tesla"
exp = parser.parseExpression("name == 'Nikola Tesla'");
boolean result = exp.getValue(tesla, Boolean.class);
// result == true
4.1.1. Understanding EvaluationContext
The EvaluationContext interface is used when evaluating an expression to resolve properties, methods, or fields and to help perform type conversion.
4.1.2. Parser Configuration
It is possible to configure the SpEL expression parser by using a parser configuration object. The configuration object controls the behavior of some of the expression components.
4.1.3. SpEL Compilation
Spring Framework 4.1 includes a basic expression compiler. Expressions are usually interpreted, which provides a lot of dynamic flexibility during evaluation but does not provide optimum performance.
4.2. Expressions in Bean Definitions
You can use SpEL expressions with XML-based or annotation-based configuration metadata for defining BeanDefinition instances.
4.2.1. XML Configuration
A property or constructor argument value can be set by using expressions.
<bean id="numberGuess" class="org.spring.samples.NumberGuess">
<property name="randomNumber" value="#{ T(java.lang.Math).random() * 100.0 }"/>
</bean>
4.2.2. Annotation Configuration
To specify a default value, you can place the @Value annotation on fields, methods, and method or constructor parameters.
public class FieldValueTestBean {
@Value("#{ systemProperties['user.region'] }")
private String defaultLocale;
}
4.3. Language Reference
This section describes how the Spring Expression Language works.
4.4. Classes Used in the Examples
This section lists the classes used in the examples throughout this chapter.