跳至主要内容

Learn Spring Expression Language

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.

评论

此博客中的热门博文

Spring Boot: Customize Environment

Spring Boot: Customize Environment Environment variable is a very commonly used feature in daily programming: used in init script used in startup configuration used by logging etc In Spring Boot, all environment variables are a part of properties in Spring context and managed by Environment abstraction. Because Spring Boot can handle the parse of configuration files, when we want to implement a project which uses yml file as a separate config file, we choose the Spring Boot. The following is the problems we met when we implementing the parse of yml file and it is recorded for future reader. Bind to Class Property values can be injected directly into your beans using the @Value annotation, accessed via Spring’s Environment abstraction or bound to structured objects via @ConfigurationProperties. As the document says, there exists three ways to access properties in *.properties or *.yml : @Value : access single value Environment : can access multi

Elasticsearch: Join and SubQuery

Elasticsearch: Join and SubQuery Tony was bothered by the recent change of search engine requirement: they want the functionality of SQL-like join in Elasticsearch! “They are crazy! How can they think like that. Didn’t they understand that Elasticsearch is kind-of NoSQL 1 in which every index should be independent and self-contained? In this way, every index can work independently and scale as they like without considering other indexes, so the performance can boost. Following this design principle, Elasticsearch has little related supports.” Tony thought, after listening their requirements. Leader notice tony’s unwillingness and said, “Maybe it is hard to do, but the requirement is reasonable. We need to search person by his friends, didn’t we? What’s more, the harder to implement, the more you can learn from it, right?” Tony thought leader’s word does make sense so he set out to do the related implementations Application-Side Join “The first implementation