Spring
June 6, 2020

M01 Q30 What is SpEL?

Spring Expression Language (SpEL) is an expression language that allows you to query and manipulate objects graphs during the runtime. SpEL is used in different products across the Spring portfolio.

SpEL can be used independently with the usage of ExpressionParser and EvaluationContext or can be used on top of fields, method parameters, constructor arguments via @Value annotation @Value("#{ … }").

SpEL expressions are usually interpreted during runtime, this is good since it provides a lot of dynamic features. However, in some cases performance is more important than a number of features available, for those cases Spring Framework 4.1 introduced the possibility to compile expressions.

Compilation of Spring Expression is done by creating real Java Class that embodies expression, this results in much faster Expression Evaluation. Because during compilation, reference types of properties are unknown, Compiled Expressions are best to use when types of referenced types are not changing.

The compiler is turned off by default, you can turn it on by:

  • Parser Configuration
  • System Property - spring.expression.compiler.mode

The compiler can operate in three modes (SpelCompilerMode):

  • Off – default
  • Immediate – compile upon first expression interpretation
  • Mixed – compiler dynamically switched between interpreted and compiled mode, the compiled form is generated after few invocations. If the exception will be thrown during compiled form evaluation, then fallback to interpreted form will occur, and then after few invocations, the compiler will switch to compiled mode again.

Compiled Mode does not support the following expressions:

  • Expressions involving assignment
  • Expressions relying on the conversion service
  • Expressions using custom resolvers or accessors
  • Expressions using selection or projection

What can you reference using SpEL?

You can reference the following using SpEL:

  • static field from class - T(com.example.Person).DEFAULT_NAME
  • static method from class - T(com.example.Person).getDefaultName()
  • Spring Bean property - @person.name
  • Spring Bean method - @person.getName()
  • SpEL Variables - #personName
  • Object property on reference assgned to SpEL variables - #person.name
  • Object method on reference assigned to SpEL variables - #person.getNames()
  • Spring Application Environment variables - environment['app.file.property']
  • System properties - systemProperties['app.vm.property']
  • System Environment Properties - systemEnvironment['JAVA_HOME']