View RSS Feed

Spring Framework

Advanced Uses of SpEL

Rate this Entry
by , 11-16-2011 at 04:50 PM (2170 Views)
There are a number of operations that you can apply on values as well as class scoped methods and constants using SpEL. Consider for example doing basic math operations on values. SpEL supports all the basic arithmetic operations that are supported in Java’s libraries. Consider that if you want to use constants or class-scoped methods you will need to use the T() operator. Below is an example of how it is to be used:


The creates a Class object that represents java.lang.Math. Now you can wire it into a bean property of type class when desired as well as access its static methods and constants. In the definition of a bean property you could use one of its static method.

Java Code:
<property name="random" value="#{T(java.lang.Math).random()}"/>
and if you want to use a constant, you can define a bean property with one of the Math’s class constants:

Java Code:
<property name="logarithmic" value="#{T(java.lang.Math).E}"/>
Other features of SpEL is the supports all of the basic math operators that are supported in Java. This includes supports for:
  • Arithmetic (+,-,*,/,%,^)
  • Relational (<, >, ==, <=, >=, lt, gt, eq, le, ge)
  • Logical (and, or, not, |)
  • Conditional (? : (ternary) )
  • Regular expression (matches)

This allows you to do a variety of things including:


Java Code:
<property name="subTotal" value="#{ + 68}"/>

Java Code:
<property name="discountedAmount" value="#{ - 50}"/>

Java Code:
<property name="squareFoot"  value="#{car.length*car.width}"/>

Java Code:
<property name="averageMileage" value="#{car.totalMileage / car.totalGas}"/>
Note also that like in normal Java, an arithmetic operator can be overloaded, so for example, the + operator is overloaded to perform concatenation on String values. You can also compare values using SpEL to do logical operations:

Java Code:
<property name="hasCapacity" value="#{car.gasMileage le 5000}"/>
As you can see, SpEL offers a le operator that doesn’t present any issues in XML. Note that you can use these to evaluate any type of value. There is alot more you can learn about SpEL. Go to your Spring documentation for more information.

Submit "Advanced Uses of SpEL" to Facebook Submit "Advanced Uses of SpEL" to Digg Submit "Advanced Uses of SpEL" to Submit "Advanced Uses of SpEL" to StumbleUpon Submit "Advanced Uses of SpEL" to Google