The Spring Expression Language (SpEL) is a simple and powerful expression language
which helps to query and manipulate objects at runtime.
We can extend SpEL by defining our own custom functions. Use registerFunction method of
StandardEvaluationContext to register a static method as SpEL custom function.
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext stdContext = new StandardEvaluationContext();
//Register a static method as CUSTOM function
stdContext.registerFunction("mysort",
SortUtil.class.getDeclaredMethod("sort", new Class[] { int [].class }));
//Function invocation int [] data = (int [])parser.parseExpression(
"#mysort({ 2, 5, 1, 3, 6, 4})").getValue(stdContext);
class SortUtil {
//Only static methods can be called via function references.
//The method 'com.bethecoder.tutorials.spring3.tests.spel.SortUtil.sort'
//referred to by name 'mysort' is not static.
//public int [] sort(int [] data) {
public static int [] sort(int [] data) {
Arrays.sort(data); return data;
}
}
It gives the following output,
Function output : [1, 2, 3, 4, 5, 6]
Function output : [1, 2, 3, 4, 5, 6]