Spring Expression Language



SPEL has following tricks and features
  • It refers beans by their ID
  • It allows to access properties and methods on the bean
  • It evaluate relational, logical and math operations on values
  • It also evaluates regular expression
  • It can also manipulate collection
Example:
#{1} : This will simply give you the constant value 1

#{T(System).currentTimeMillis()}
This expression will call the static method currentTimeMillis(). It will evaluate T to  java.lang.System class

#{userData.name}
This  expression will use the userData bean and access its name property

SPEL Inside constructor in Class
Inside the constructor of FileData SPEL will get the values for title and Author from the system properties and it will assign values to title and author arguments.
public FileData(
    @Value("#{systemProperties['file.title']}") String title,
    @Value("#{systemProperties['file.author']}") String author) {
    this.title = title;
    this.author = author;
}


SPEL in XML bean tag
<bean id="fileData"
class="user.FileData"
c:_title="#{systemProperties['file.title']}"
c:_artist="#{systemProperties['file.artist']}" /> 


Other Examples
#{1.19159}
#{9.98E4}
#{'Java World'}
#{false}
#{true}
#{fileData.selectAuthor()}
#{fileData.selectAuthor().toUpperCase()}
#{11 * T(java.lang.Math).PI * circleData.getRadius()}
#{items.total == 90} or  #{items.total eq 90}

Ternary Operator
#{student.score > 50 ? "Pass!" : "Fail"}


String concatenation
#{fileData.title + ' by ' + fileData.author}

To protect is from a NullPointerException, we can use the SPEL type-safe operator: ?.
#{fileData.selectAuthor()?.toUpperCase()}

Regular Expression
#{userData.email matches '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.com'}

Take Element from List
#{students.books[4].title}

Take character from String
#{'This is a test'[7]}

Filter Collection into Subset using Operator: .?[]
#{students.subjects.?[subject eq 'math']}

Operator to select first match: .^[]
#{artist.songs.^[song eq 'titanic']}

Take particular property from collection object using projection operator : .![]
#{artist.songs.![name]} 
This will give you the name collection from the songs collection