When reading the source code of some Spring based projects, we can see some code like following:
@Value("${env}")
private int value;
and like following:
@Autowired
public void configure(MovieFinder movieFinder,
@Value("#{ systemProperties['user.region'] }") String defaultLocale) {
this.movieFinder = movieFinder;
this.defaultLocale = defaultLocale;
}
In this way, we can inject values from different sources very conveniently, and this is the features of Spring EL.
What is Spring EL? How to use this handy feature to assist our developments? Today, we are going to learn some basics of Spring EL.
Features
The full name of Spring EL is Spring Expression Language, which exists in form of Java string and evaluated by Spring. It supports many syntax, from simple property access to complex safe navigation – method invocation when object is not null. And the following is the feature list from Spring EL document:
- Literal expressions;
- Boolean and relational operators;
- Regular expressions;
- Class expressions and constructor;
- Accessing properties, arrays, lists, maps;
- Method invocation;
- Assignment;
- Bean reference;
- Array construction;
- Inline lists and maps;
- Ternary operator;
- Collection project & selection;
- Templated expression;
Context
The expression is evaluated under certain context, either in the context of whole project, or user defined context:
Inventor tesla = new Inventor("Nikola Tesla");
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("name");
EvaluationContext context = new StandardEvaluationContext(tesla);
String name = (String) exp.getValue(context);// "Nikola Tesla"
The expression will be evaluate against the root object, which is in the evaluation context, in this example, tesla
. In case of not fixed root object in context, we can avoid using conext:
String name = (String) exp.getValue(tesla);
Compiler
Expression are usually evaluated by interpreter which provides dynamic flexibility:
and compiler provide better performance for complex expression:
someArray[0].someProperty.someOtherProperty < 0.1
Now, the compiler still has some limitation and fail to compile some expressions like assignment, collection selection/projection etc.
Default
The Elvis operator and safe navigation is two ways to get the default value or replacement when some condition is not met. It is like the shorthand of ternary operator:
// if name is not defined, use "unknown" instead
name?:"unknown"
// if someone is null, not throw NPE
someone?.birth
Selection and Projection
The syntax of selection and projection of Spring EL is not from Java and it is very powerful, so let’s see a few examples:
// filter list by nationality of people, in which has property of `nationality`
List<People> list = (List<People>) parser.parseExpression(
"Members.?[Nationality == 'Serbian']").getValue(societyContext);
// filter map by value
Map newMap = parser.parseExpression("map.?[value<27]").getValue();
// projection of people's nationality
List nationality = (List)parser.parseExpression("Members.![nationality]");
Problems
Dollar vs Sharp
From this questions in SO, we can see that:
#{}
: it is used only by Spring EL and lazy evaluated;${}
: it is can only used by reference properties;
New Collection
New collection can be created by constructor, but remember to use full qualified class name in order to let parser find the right class:
new java.util.HashMap();
Temp Variable
We can set the temp variable using #
:
#tmp = new java.util.HashMap()
and reuse it later with same syntax:
#tmp.put('des', 'test');
Spring EL has two pre-defined variable:
#root
: refer to the root object of context;#this
: refer to current evaluated object;
Examples cited from Spring document:
// create an array of integers
List<Integer> primes = new ArrayList<Integer>();
primes.addAll(Arrays.asList(2,3,5,7,11,13,17));
// create parser and set variable 'primes' as the array of integers
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
context.setVariable("primes",primes);
// all prime numbers > 10 from the list (using selection ?{...})
// evaluates to [11, 13, 17]
List<Integer> primesGreaterThanTen = (List<Integer>) parser.parseExpression(
"#primes.?[#this>10]").getValue(context);
Temp Function
We can even register a temporary methods in the following way:
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
context.registerFunction("reverseString",
StringUtils.class.getDeclaredMethod("reverseString", new Class[] { String.class }));
Then, we can invoke reverseString
like we refer to a temp variable using #
:
String helloWorldReversed = parser.parseExpression(
"#reverseString('hello')").getValue(context, String.class);
Space in Expression
The following shows a strange behavior of Spring EL, the space in the expression string affect the result of expression:
"#{#tags?.split('\n')}" -> parse to array
"#{#tags?.split('\n')} " -> parse to string, array elements connected by ","
No \0
When we try to use tags.split('\0')
this expression, we find it can’t work. We first think it’s the wrong number of slash because in Java string regex representation can be tricky:
"tags".split("\\\0")
But when we try all possible slash, we still get exceptions like InternalParseException
and SpelParseException
which complains Cannot find terminating '' for string
or Cannot find terminating " for strin
.
Searching the web give me no results, we have to debug the source code. Finally, in the Tokenizer
source code, we find it take \0
as the end symbol which make it fail to parse any Java string which contains \0
.
while (!terminated) {
this.pos++;
char ch = this.toProcess[this.pos];
if (ch == '\'') {
// may not be the end if the char after is also a '
if (this.toProcess[this.pos + 1] == '\'') {
this.pos++; // skip over that too, and continue
}
else {
terminated = true;
}
}
if (ch == 0) {
throw new InternalParseException(new SpelParseException(this.expressionString, start,
SpelMessage.NON_TERMINATING_QUOTED_STRING));
}
}
We have created a Jira issue for Spring and provide a pull request, hope it will soon be solved.
Written with StackEdit.
评论
发表评论