Spring Expression Language

The Spring Expression Language or SpEL is an expression language that is used for querying in the application. It was designed for the p purpose to suit a well-supported expression language for the Spring framework. We can use it with both types of configuration XML and annotation. It can be used to inject a bean or a bean property into another bean. It is a rich set of functionality that allows the following features.

  • Literal expressions

  • Variables

  • Boolean and relational operators

  • Accessing properties, arrays, lists, and maps

  • Method invocation

  • Relational operators

  • Assignment

  • Calling constructors

  • Bean references

  • Inline lists

  • Ternary operator

Time for Examples

Let's see some useful examples to use expression language in the spring application.

Expression Language for Literal Expression

We can use expression language to set the literals value for bean property. See, we used curly braces to enclose the literal value and assigned it to the value attribute. We can do the same with Java code as well by using the @Value annotation. We have added examples for both.

<!-- XML Code  -->
<bean id="user" class="com.studytonight.User">
  <property name="id" value = "#{'1021'}" />
</bean>


<!-- Java Code -->
package com.studytonight;
class User{
   @Value("#{1021}")
   int id;
   @Value("#{'Rohan'}")
   String name;
...
}

Expression Language for Variable

We can pass variables inside the curly braces to set value for the property. We can use it to get value from the property file by just parsing the variable.

package com.studytonight;
class User{
   @Value("#{user.id}")
   int id;
   @Value("#{'user.name'}")
   String name;

...

}

Expression Language for Operators

Expression language allows using operators in expression to set the value. You can see that a boolean value will be set to the property after the expression is evaluated.

package com.studytonight;
class Demo{
   @Value("#{a<b}")
   private boolean isGreater;

   @Value("#{a<b?true:false}")
   private boolean check;
...
}

Expression Language for Method Invocation

We can call any method within the curly braces because the Expression Language allows the method invocation feature to make it more dynamic. See the example below.

package com.studytonight;
class User{
   @Value("#{user.id}")
   int id;
   @Value("#{'user.name'.toUpperCase()}")
   String name;
...
}

Expression Language in JSP Page

This is most of the case when we need to use expression language. Spring works with JSP and Expression language works well for querying data, making dynamic expressions, and showing dynamic data to the user.

<body>
<strong>Hello,</strong>
<h2>${user.name}</h2>
</body>