Cheap VPS & Xen Server


Residential Proxy Network - Hourly & Monthly Packages

SPEL Examples


SpEL is an exression language supporting the features of querying and manipulating an object graph at runtime.

There are many expression languages available such as JSP EL, OGNL, MVEL and JBoss EL. SpEL provides some additional features such as method invocation and string templating functionality.

SpEL API

The SpEL API provides many interfaces and classes. They are as follows:

  • Expression interface
  • SpelExpression class
  • ExpressionParser interface
  • SpelExpressionParser class
  • EvaluationContext interface
  • StandardEvaluationContext class

Hello SPEL Example

  1. import org.springframework.expression.Expression;
  2. import org.springframework.expression.ExpressionParser;
  3. import org.springframework.expression.spel.standard.SpelExpressionParser;
  4. public class Test {
  5. public static void main(String[] args) {
  6. ExpressionParser parser = new SpelExpressionParser();
  7. Expression exp = parser.parseExpression(“‘Hello SPEL'”);
  8. String message = (String) exp.getValue();
  9. System.out.println(message);
  10. //OR
  11. //System.out.println(parser.parseExpression(“‘Hello SPEL'”).getValue());
  12. }
  13. }
download this example (developed using MyEclipse IDE)

Other SPEL Example

Let’s see a lot of useful examples of SPEL. Here, we are assuming all the examples have been written inside the main() method.

Using concat() method with String

  1. ExpressionParser parser = new SpelExpressionParser();
  2. Expression exp = parser.parseExpression(“‘Welcome SPEL’.concat(‘!’)”);
  3. String message = (String) exp.getValue();
  4. System.out.println(message);

Converting String into byte array

  1. Expression exp = parser.parseExpression(“‘Hello World’.bytes”);
  2. byte[] bytes = (byte[]) exp.getValue();
  3. for(int i=0;i<bytes.length;i++){
  4.     System.out.print(bytes[i]+” “);
  5. }

Getting length after converting string into bytes

  1. Expression exp = parser.parseExpression(“‘Hello World’.bytes.length”);
  2. int length = (Integer) exp.getValue();
  3. System.out.println(length);

Converting String contents into uppercase letter

  1. Expression exp = parser.parseExpression(“new String(‘hello world’).toUpperCase()”);
  2. String message = exp.getValue(String.class);
  3. System.out.println(message);
  4. //OR
  5. System.out.println(parser.parseExpression(“‘hello world’.toUpperCase()”).getValue());

Comments

comments