Spring expression language: Spel syntax

Source: Internet
Author: User
Tags new set

Spring expression language abbreviation: Spel,spel can be used independently of the spring container, or can be used in the spring configuration file, which greatly simplifies the bean configuration of spring, and gives the configuration file a "weight loss" role, the following summarizes the SPEL syntax

1: Direct-Volume expression

The direct-volume expression is also the simplest expression of spel, as follows:

public class Spelgrammar {public static void main (String[]args) {        //Creates a ExpressionParser object, Used to parse the expression expressionparser parser = new Spelexpressionparser ();//Use the direct amount expression Expressions exp = parser.parseexpression ("' Vipmao "); System.out.println (Exp.getvalue (string.class)); exp = parser.parseexpression ("6.9"); System.out.println (Exp.getvalue (Double.class));}}

Operation Result:

Vipmao

6.9

2: Create an array in an expressionSpel Creating arrays is no different from regular creation, and Spel also supports both static and dynamic creation.
public static void Main (String[]args) {        //Create a ExpressionParser object to parse the expression expressionparser parser = new Spelexpressionparser ();//------------Create an array with Spel Expression exp=parser.parseexpression ("New string[]{" Struts2 ', ' Hibernate ', ' Spring '} '); System.out.println (Exp.getvalue (String.class));//Create a two-dimensional array exp = parser.parseexpression ("New int[2][4]"); System.out.println (Exp.getvalue (Int.class));}}
Operation Result:struts2,hibernate,spring
03: Create a list collection in an expressionSpel supports direct use of {ele1,ele2,ele3 ...} syntax to create a list collection, but it is not able to modify the elements within the collection.
public class Spelgrammar {public static void main (String[]args) {               //Creates a ExpressionParser object, Used to parse an expression expressionparser parser = new Spelexpressionparser ();//------------Create an array with Spel expression exp= Parser.parseexpression ("{' Java ', ' C language ', ' PHP '}"); System.out.println (Exp.getvalue (String.class));//Create a "two-dimensional" list set exp = Parser.parseexpression ("{' Monkey King ', ' a ', '"}, {' Liu Bei ', ' Zhuge Liang '}} "); System.out.println (Exp.getvalue ());}}

Operation Result:Java,c language, PHP
[[Sun Wukong], [Liu Bei, Zhuge Liang]]4:spel access to the list, map, and other elements collectionAccessing the list collection elements through List[index] in Spel, and accessing the map collection elements through Map[key], let's create a collection by general, modify their collection elements, and access specific collection elements.
public class Spelgrammar {public static void main (String[]args) {//Creates a ExpressionParser object to parse the expression Expressio Nparser parser = new Spelexpressionparser ();//------------use Spel to create an array-----------//------------use Spel to access the list collection, The elements of the map collection-----------list<string>list=new arraylist<string> (); List.add ("Java"); List.add ("PHP"); Map<string,double>map=new hashmap<string,double> (); Map.put ("math", 78.8); Map.put ("Chinese", 98.6); Map.put ("中文版", 92.2);//Create a Evaluationcontext object as the context of the SPEL parsing variable evaluationcontext ctx = new Standardevaluationcontext ();//Set two variables ctx.setvariable ("list", list), ctx.setvariable ("MyMap", map);// Modify and access the collection parser.parseexpression ("#list [0]"). SetValue (CTX, "Java ee");p arser.parseexpression ("#myMap [' math ']"). SetValue (CTX, 99.9); System.out.println ("The first element in the list collection is:" +parser.parseexpression ("#list [0]"). GetValue (CTX)); SYSTEM.OUT.PRINTLN ("The modified value in map is:" +parser.parseexpression ("#myMap [' math ']"). GetValue (CTX));}}
We use the setvariable () to set the collection to a variable of context, modify the value of the specified collection through SetValue (), and get the value of the specified collection by GetValue.
Operation Result:
The first element in the list collection is: Java EE
The modified value in map is: 99.95: Call Methodthere is no big difference between calling a method and normal
public class Spelgrammar {public static void main (String[]args) {                //Creates a ExpressionParser object, Used to parse the expression expressionparser parser = new Spelexpressionparser ();//------------Use Spel call method-----------// Call the substring () method of the String Object System.out.println (Parser.parseexpression ("' Vipmao '. substring (0,3)"). GetValue ()); List<string>list=new arraylist<string> (); List.add ("Java"); List.add ("PHP");//Create a Evaluationcontext object , as the context of the SPEL parsing variable evaluationcontext ctx = new Standardevaluationcontext ();//Set two variable ctx.setvariable ("list", list); System.out.println (Parser.parseexpression ("#list. Sublist (0,2)"). GetValue (CTX));}}

Operation Result:
Vip
[Java, PHP]6: Arithmetic, comparison, assignment, ternary operator
public class Spelgrammar {public static void main (String[]args) {               //------------use operator in Spel-----------               // Creates a ExpressionParser object to parse the expression expressionparser parser = new Spelexpressionparser (); List<string>list=new arraylist<string> (); List.add ("Java"); List.add ("PHP");//Create a Evaluationcontext object , as the context of the SPEL parsing variable evaluationcontext ctx = new Standardevaluationcontext ();//Set two variable ctx.setvariable ("list", list); Parser.parseexpression ("#list [0]= ' Java ee '). GetValue (CTX); System.out.println (Parser.parseexpression ("#list"). GetValue (CTX));//Use the ternary operator SYSTEM.OUT.PRINTLN ( Parser.parseexpression ("#list. Size () >3?" MyList length greater than 3 ': ' MyList length not greater than 3 ' "). GetValue (CTX));}}
we can see that the above program is directly assigned to the first element of the collection through #list[0]= ' Java EE, and also uses the ternary operator A>B?A:B
Operation Result:
[Java EE, PHP]
MyList length not greater than 37: type operatorSpel provides a special operator: T (), which tells Spel to treat the string inside the operator as "class", avoiding other processing by spel, especially when a static method of a class is called, and the T () operator is particularly useful.
public class Spelgrammar {public static void main (String[]args) {//Creates a ExpressionParser object to parse the expression ExpressionParser Parser = new Spelexpressionparser ();//------------Use the type operator in Spel-----------//Call the static method of math System.out.println ( Parser.parseexpression ("T (Java.lang.Math). Random ()"). GetValue ());//static method that calls Math System.out.println ( Parser.parseexpression ("T (System). GetProperty (' Os.name ')"). GetValue ());}}

in our program, we pass T (Java.lang.Math). Random () Gets the Math class's random () method to randomly get a number, it is important to note that T () in parentheses recommend the use of the fully qualified class name, that is, write on the package name, if not written, Spel will look for these classes by default under the Java.lang package. Operation Result:
0.6289150409783065
Windows 7
8: Call constructorSpel can call the constructor directly from new, creating a Java object in this way
public class Spelgrammar {public static void main (String[]args) {//Creates a ExpressionParser object to parse the expression ExpressionParser Parser = new Spelexpressionparser (),//------------The constructor is called in Spel-----------System.out.println (parser.parseexpression ("New String (' HelloWorld '). SUBSTRING (2, 4)"). GetValue ()); System.out.println (Parser.parseexpression ("New Javax.swing.JFrame (' Test '). setvisible (' true ')"). GetValue ());}}

creates a string string HelloWorld with new and calls substring () to intercept stringsOperation Result:
LL
Null
and a form9: Safe navigation operationsafe navigation, listen to the meaning is to prevent errors, such as person.name this statement, if the person object is already empty, then name will definitely report null pointer NullPointerException exception, in order to avoid, in Spel can write this Person?. Bar, if person is empty, return empty directly, program no longer go down, will not report NullPointerException exception
Import Java.util.*;import Org.springframework.expression.*;import Org.springframework.expression.common.templateparsercontext;import Org.springframework.expression.spel.standard.spelexpressionparser;import Org.springframework.expression.spel.support.standardevaluationcontext;public class SpelGrammar {public static void Main (String[]args) {//Creates a ExpressionParser object for parsing the expression expressionparser parser = new Spelexpressionparser ();//-------- ----Use secure navigation in Spel-----------//Use safe operation to output NULLSYSTEM.OUT.PRINTLN ("---" +parser.parseexpression ("#foo?. Bar "). GetValue ()//Do not use secure operation, the NullPointerException exception System.out.println (parser.parseexpression (" #foo. Bar ") is thrown. GetValue ());}}

The first output statement uses the safe navigation operation #foo?. Bar will output empty, but the second statement will not use the safe navigation operation would be an error. 10: Selection of the collectionSpel through collection.? [CONDITION_EXPR] Filters the collection according to specific filter criteria. Only collections that meet the criteria will be filtered out.
public class Spelgrammar {public static void main (String[]args) {//Creates a ExpressionParser object to parse the expression ExpressionParser Parser = new Spelexpressionparser (); List<string>list=new arraylist<string> (); List.add ("Java"); List.add ("PHP"); List.add ("JavaScript"); Map<string,double>map=new hashmap<string,double> (); Map.put ("math", 92.8); Map.put ("Chinese", 98.6); Map.put ("中文版", 92.2);//Create a Evaluationcontext object as the context of the SPEL parsing variable evaluationcontext ctx = new Standardevaluationcontext ();//Set two variables ctx.setvariable ("list", list), ctx.setvariable ("MyMap", map);// A list collection element of length greater than 7 will be filtered out expression expr=parser.parseexpression ("#list.? [Length () >7] "); System.out.println ("The list element that meets the criteria is:" +expr.getvalue (CTX)),//key's length is less than 5 and the value>90 map element is filtered out expr= Parser.parseexpression ("#myMap.? [Key.length () <5&&value>90] "); SYSTEM.OUT.PRINTLN ("The Eligible map value is:" +expr.getvalue (CTX));}}
program to list collection, map collection through collection. [condition_expr] is filtered, it is important to note that when you manipulate the map collection, you need to explicitly use key to reference the map entry key, using value to refer to the value of map entry , For example, we filter condition is: Map key length needs less than 5, that is #mymap. [Key.length () <5]. If our filter is: The value of MAP value is greater than 90, that is #myMap. [Value>90]. If the filter conditions need to meet the above two conditions are: #myMap.? [Key.length () <5&&value>90] Operation Result:
The list element that meets the criteria is: [JavaScript]
The map value that meets the criteria is: {math=92.8}

11: Projection of the collectionSet projection is the original set in accordance with a certain "projection condition" of the original set of each element of the projection, the "projection of the Shadow" into a new collection, it is not the same as the filter of the collection, filtering is filtered out to meet the conditions of the set elements, but does not constitute a new collection, but the projection needs to be composed of a syntax format for spel projection operations:collection.! [condition_expr], like collection filtering, is the filter? , is it not eligible? The match is filtered out, while the projection is!.
public class Spelgrammar {public static void main (String[]args) {//Creates a ExpressionParser object to parse the expression ExpressionParser Parser = new Spelexpressionparser (); List<string>list=new arraylist<string> (); List.add ("Java"); List.add ("PHP"); List.add ("JavaScript");// Create a Evaluationcontext object as the context of the SPEL parsing variable evaluationcontext ctx = new Standardevaluationcontext ();// Set the variable ctx.setvariable ("list", list);//------------projection of the collection in Spel-----------//intercept each collection element to form a new set of expression expr= Parser.parseexpression ("#list.! [substring (1,3)] "); System.out.println ("The new collection after projection is:" +expr.getvalue (CTX)); List<person>list2=new arraylist<person> () list2.add (new person (1, "Vipmao",]) List2.add (New person ( 2, "Zhulin"), Ctx.setvariable ("Mylist2", List2); Expr=parser.parseexpression ("#mylist2"); System.out.println ("The collection before the projection is:" +expr.getvalue (CTX));//the projection condition is as long as the Name property Expr=parser.parseexpression ("#mylist2.! [Name] "); System.out.println ("The new collection after projection is" +expr.getvalue (CTX));}}
The above through the projection conditions of each element of the collection is projected, and then formed a new set, the above also said that the projection and filtering, filtering is to meet the criteria of the collection elements to filter, not satisfied with the direct skip, but the projection does not, he needs to complete the projection of each set element, If there is a set of elements, can not meet the projection conditions cause the projection failure, the program will error, such as we will be the first set projection condition to intercept 2-5 length, but Java, PHP, the length of less than 5, then the error. The second collection uses the Person class, the following
public class Person {private Integer id;private string name;private int weight;public person (Integer ID, String name, int Weight) {this.id = Id;this.name = Name;this.weight = weight;} Omit all set, get method public String toString () {return ' ID: "+id+", Name: "+name+", Weight: "+weight;}}
Operation Result:
the new collection after projection is: [AV, HP, av]
The collection before the projection is: [id:1,name:vipmao,weight:130, id:2,name:zhulin,weight:105]
The new collection after projection is [Vipmao, Zhulin]
As can be seen from the results, the corresponding set has been formed according to the projection conditions.

12: expression templateinternationalization messages that are somewhat similar to placeholders
public class Spelgrammar {public static void main (String[]args) {//Creates a ExpressionParser object to parse the expression ExpressionParser Parser = new Spelexpressionparser ();//------------Use an expression template in Spel-----------person p1 = new person (1, "Monkey King", 120); person P2 = new Person (2, "pig", 220); Expression EXPR3 = parser.parseexpression ("My Name is #{name}" + ", Weight is #{weight}", New Templateparsercontext ());// The #{}system.out.println (Expr3.getvalue (p1)) in the expression template above will be populated with the P1 object name and height, and//will be populated with P2 object name, height, and #{} in the expression template above System.out.println (Expr3.getvalue (P2));}}

using an expression template requires passing in a templateparsercontext parameterOperation Result:
My name is Monkey King, weight is 120
My name is pig, and the weight is 220.

Spring expression language: Spel syntax

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.