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

This Variable 

The Spring Expression Language (SpEL) is a simple and powerful expression language which helps to query and manipulate objects at runtime. The following example shows using this variable (#this) for the selection of odd and even numbers. Refer Collection Selection tutorials to know more on selection operator.

File Name  :  
com/bethecoder/tutorials/spring3/tests/spel/ThisVariableTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.spring3.tests.spel;

import java.util.Arrays;
import java.util.List;

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

public class ThisVariableTest {

  /**
   @param args
   */
  public static void main(String[] args) {

    List<Integer> nums = Arrays.asList(12345678);
    System.out.println("Numbers : " + nums);
    
    ExpressionParser parser = new SpelExpressionParser();
    StandardEvaluationContext stdContext = new StandardEvaluationContext();
    stdContext.setVariable("nums", nums);

    //Filter Even numbers from the list (using selection ?{...})
    List<Integer> evenNums = 
      (List<Integer>parser.parseExpression("#nums.?[#this % 2 == 0]").getValue(stdContext);
    System.out.println("Even Numbers : " + evenNums);

    //Filter Odd numbers from the list (using selection ?{...})
    List<Integer> oddNums = 
      (List<Integer>parser.parseExpression("#nums.?[#this % 2 == 1]").getValue(stdContext);
    System.out.println("Odd Numbers : " + oddNums);
    
  }

}
   

It gives the following output,
Numbers : [1, 2, 3, 4, 5, 6, 7, 8]
Even Numbers : [2, 4, 6, 8]
Odd Numbers : [1, 3, 5, 7]



 
  


  
bl  br