In this post under Spring SpEL, I will explain with example what is “Expression Templating”.
Expression Templating is a way by which we can mix literal text with one or more SpEL expressions and create a String template. At runtime the expressions in the template are replaced by actual value.
Each expression in the String template are surrounded by “#{” and “}”.
Below is an example for your reference
String randomPhrase = "random number is #{T(java.lang.Math).random()}".
Below is the main class showing how to use the expression template in java code.
Main class
package spel.package17;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import java.util.ArrayList;
import java.util.List;
public class Example17 {
@Value("The list has #{integerList.?[intValue()%2 == 0].size()} even numbers and #{integerList.?[intValue()%2 != 0].size()} odd numbers")
private String result;
@Bean("integerList")
public List<Integer> getIntegerList() {
List<Integer> list = new ArrayList<>(0);
for(int i = 0; i < 10; i++) {
list.add(i);
}
return list;
}
public static void main(String args[]) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example17.class);
Example17 example17 = applicationContext.getBean(Example17.class);
System.out.println(example17.result);
}
}
In the above code, at line 12, I created an expression.
In the expression, “integerList” is a bean of type List created using method “getIntegerList”. Refer to line 15 to 22.
The bean “integerList” consists of 10 integers.
When an instance of “Example17” is created by Spring container, the expression template is evaluated and the result is stored in “result” String variable.
At line 27, I print the “result” variable content to the console.
In this way we can mix literal text with SpEL expressions.