Home  >  Spring Core

Register User Defined Functions in Spring Expression Language

By Arvind Rai, October 09, 2013
StandardEvaluationContext.registerFunction registers user defined function to work as spring expression language. To do this creates your own class and methods that need to be register. In our example we are defining a method that take input as string and return the length + 10. Find the example below.

SpELTest.java
package com.concretepage;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
public class SpELTest {
	public static void main(String[] args) throws SecurityException, NoSuchMethodException {
		ExpressionParser parser = new SpelExpressionParser();
		StandardEvaluationContext seContext = new StandardEvaluationContext();
    	seContext.registerFunction("getStringLen",StringLength.class.getDeclaredMethod("getStringLen", 
          new Class[] { String.class }));
		Integer len =  parser.parseExpression("#getStringLen('concretepage.com')").getValue(seContext, Integer.class);
		System.out.println(len);
	}
}
abstract class StringLength {
	  public static int getStringLen(String str) {
	    return str.length()+10;
	  }
}
 
Output
26
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us