Open Tao Spring3 (5.1&5.2)-Spring Expression Language 5.1 Overview 5.2 Spel Basics

Source: Internet
Author: User

5.1 Overview 5.1.1 Overview

Spring expression language is all called "Spring expression Language", abbreviated as "Spel", similar to the OGNL expression language used in struts2x, can build complex expressions at run time, Access object graph properties, object method calls, etc. And can be perfectly integrated with spring functionality, such as the ability to configure Bean definitions.

The expression language adds dynamic functionality to the static Java language.

Spel is a standalone module that relies only on the core module and does not depend on other modules and can be used alone.

What can 5.1.2 do?

Expression language is generally the simplest form of accomplishing the most important work, reducing our workload.

Spel supports the following expressions:

basic expression: literal expression, relation, logic and arithmetic expression, string connection and intercept expression, trinocular operation and elivis expression, regular expression, bracket precedence expression;

Class -Related expressions: class-type expressions, class instantiation, instanceof expressions, variable definitions and references, assignment expressions, custom functions, object property access and safe navigation expressions, object method calls, bean references;

three, set related expressions: inline list, inline array, collection, dictionary access, list, dictionary, array modification, set projection, collection selection; no support for multidimensional inline array initialization; Inline dictionary definitions are not supported;

Iv. Other Expressions : template expressions.

Note: Spel the keywords in an expression are case-insensitive.

5.2 Spel Basic 5.2.1 HelloWorld

First prepare the jar package that supports Spel: "Org.springframework.expression-3.0.5.release.jar" to add it to the classpath.

Spel is generally divided into four steps in the expression value, the third step is optional: First constructs a parser, followed by the parser parse the string expression, in this construction context, finally according to the context to get the value of the expression after the operation.

Let's take a look at the code snippet:

 PackageCn.javass.spring.chapter5;ImportJunit.framework.Assert;Importorg.junit.Test;ImportOrg.springframework.expression.EvaluationContext;Importorg.springframework.expression.Expression;ImportOrg.springframework.expression.ExpressionParser;ImportOrg.springframework.expression.spel.standard.SpelExpressionParser;ImportOrg.springframework.expression.spel.support.StandardEvaluationContext; Public classspeltest {@Test Public voidHelloWorld () {ExpressionParser parser=NewSpelexpressionparser (); Expression Expression=Parser.parseexpression ("(' Hello ' + ' world '). Concat (#end)"); Evaluationcontext Context=NewStandardevaluationcontext (); Context.setvariable ("End", "!"); Assert.assertequals ("Hello world!", Expression.getvalue (context)); }}

Next, let's Analyze the code:

1) Create parser: Spel uses ExpressionParser interface to represent the parser, providing spelexpressionparser default implementation;

2) Parse expression: Use ExpressionParser's parseexpression to parse the corresponding expression as an expressions object.

3) Construct context: Prepare the contextual data required for expressions such as variable definitions, and so on.

4) Evaluation: The expression value is derived from the context using the GetValue method of the expression interface.

is not very simple, then let us look at its specific implementation and principles of it.

5.2.3 Spel principle and interface

Spel provides a simple interface that simplifies user use, and lets us learn the next few concepts before introducing the principle:

Expression : expression is the core of the expression language, so the expression language is all around the expression, from our point of view is "doing";

Second, parser: used to parse a string expression into an expression object, from our point of view is "who to do";

Iii. Context: an environment in which an expression object executes, which may define variables, define custom functions, provide type conversions, and so on, from our point of view is "where to do";

The root object and the activity context object: The root object is the default active context object, and the activity context object represents the object of the current expression operation, from our point of view is "who to do".

After understanding these concepts, let's look at how Spel works, as shown in 5-1:

Figure 5-1 How it works

1) First define an expression: "1+2";

2) Define the parser ExpressionParser implementation, Spel provide the default implementation spelexpressionparser;

2.1) Spelexpressionparser parser uses Tokenizer class for lexical analysis, that is, the string stream is analyzed as a tick stream, and the notation is represented by token class in Spel;

2.2) with a tick stream, the parser can generate an internal abstract syntax tree based on the tick flow; in Spel, the syntax tree node is represented by the Spelnode interface: For example, Opplus represents an int literal node, and the IntLiteral represents the ; using Spelnodel to make up the abstract syntax tree;

2.3) Provide an expression interface to simplify the representation of the abstract syntax tree, thus hiding the internal implementation details, and provide GetValue simple method to get the expression value; Spel provides a default implementation of Spelexpression;

3) Define the expression context object (optional), Spel uses the Evaluationcontext interface to represent the context object, which is used to set the root object, custom variables, custom functions, type converters, etc. SPEL provides default implementation standardevaluationcontext;

4) Use an expression object to obtain the result based on the context object (optional) evaluation (called the GetValue method of the Expression object).

Next, let's look at the main interface of Spel:

1 ) ExpressionParser interface : Represents the parser, and the default implementation is the Spelexpressionparser class in the Org.springframework.expression.spel.standard package. Use the ParseExpression method to convert a string expression to an expression object, for the ParserContext interface to define whether a string expression is a template, and the template starts with the end character:

     Public Interface ExpressionParser {             Expression parseexpression (String expressionstring);             Expression parseexpression (String expressionstring, ParserContext context);      }  

Take a look at the example:

@Test Public voidTestparsercontext () {ExpressionParser parser=NewSpelexpressionparser (); ParserContext ParserContext=NewParserContext () {@Override Public Booleanistemplate () {return true; } @Override PublicString Getexpressionprefix () {return"#{"; } @Override PublicString Getexpressionsuffix () {return"}";    }    }; String Template= "#{' Hello '}#{' world! '}"; Expression Expression=parser.parseexpression (template, ParserContext); Assert.assertequals ("Hello world!", Expression.getvalue ());}

Here we demonstrate the use of ParserContext, where the ParserContext implementation is defined: The definition expression is a module, the expression prefix is "#{", the suffix is "}", and the template passed in with ParseExpression parsing must start with "#{". End With "}", such as "#{' Hello '}#{' world! '}".

The default passed-in string expression is not a template form, such as Hello World, which was previously demonstrated.

2 ) Evaluationcontext interface : Represents the context environment, and the default implementation is the Standardevaluationcontext class in the Org.springframework.expression.spel.support package. Use the Setrootobject method to set the root object, use the SetVariable method to register the custom variable, use Registerfunction to register the custom function, and so on.

3 ) Expression Interface: represents an Expression object, The default implementation is spelexpression in the Org.springframework.expression.spel.standard package, which provides getvalue methods for getting expression values, and provides SetValue methods for setting object values.

Understanding the Spel principle and interface, the next thing is Spel grammar.

Open Spring3 (5.1&5.2)-Spring Expression Language 5.1 Overview 5.2 Spel Basics

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.