tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 
 Spring > Expression Language > Functions

Functions 

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.

File Name  :  
com/bethecoder/tutorials/spring3/tests/spel/FunctionTest.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
package com.bethecoder.tutorials.spring3.tests.spel;

import java.util.Arrays;

import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class FunctionTest {

  /**
   @param args
   @throws NoSuchMethodException 
   @throws SecurityException 
   */
  public static void main(String[] argsthrows SecurityException, NoSuchMethodException {

    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);
    
    System.out.println("Function output : " + Arrays.toString(data));
    
    //Function invocation on variables
    stdContext.setVariable("input"new int [] { 31642});
    data = (int [])parser.parseExpression(
        "#mysort(#input)").getValue(stdContext);
    
    System.out.println("Function output : " + Arrays.toString(data));
  }

}

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]


                    Print

   



Books Recommendation

 
 
bl  br