Spring Expression Language (SpEL)

Spring Expression Language Spring Expression Language (referred SpEL) is a query and manipulate the object graph expression language runtime support. EL expression syntax is similar, but offers additional features explicit method calls and basic functions such as string template.

Although the basis SpEL Spring family expression evaluation, but it can be used independently.

Was added 1-dependent
first added in pom.xml dependency:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-expression</artifactId>
    <version>${spring.version}</version>
</dependency>

2 simple example
here, we define a simple summation of arithmetic expressions to parse SpEL:

ExpressionParser parser = new SpelExpressionParser();
Expression expression = parser.parseExpression("6+2");
Integer result = (Integer) expression.getValue();
System.out.println("result:" + result);

Output:

result:8

3 core interface
SpEL related classes and interfaces defined in the package org.springframework.expression, the sub packet and spel.support.

Analytical expressions for the interface ExpressionParser string. Expression interface is used to calculate the value of the string expressions. When you call ExpressionParser # parseExpression () may throw ParseException; when you call Expression # getValue () EvaluationException may throw an exception.

SpEL support method calls, access the properties and invoke constructors and other characteristics.

For example, we can add concat method in a string expression to concatenate strings:

ExpressionParser parser = new SpelExpressionParser();
Expression expression = parser.parseExpression("'SpEL'.concat(' thinking')");
String result = (String) expression.getValue();
System.out.println("result:" + result);

Output:

result:SpEL thinking

Since expression.getValue () returns Object, it must be an explicit conversion. We can use the public <T> T getValue (Class <T> desiredResultType), to obtain the value of the corresponding gracefully type.

String result = expression.getValue(String.class);

SpEL applied more often getting a property value of a class instance. Suppose we have an Account class:

public class Account {
    private String name;
    public Account(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
}

We have to get the name value of the Account instance by the expression:

Account account=new Account("Deniro");
ExpressionParser parser = new SpelExpressionParser();
EvaluationContext context=new StandardEvaluationContext(account);
Expression expression = parser.parseExpression("name");
String result = expression.getValue(context,String.class);
System.out.println("result:" + result);

Output:

result:Deniro

You can refer to the root object in the expression property, when the analytical expression, uses the value of the attribute acquired reflections from objects within the root.

SpEL when used alone, ExpressionParser create a parser, and a EvaluationContext evaluation context. However, the Spring Framework, only need to configure a SpEL expression (defined in the bean Spring) to. SpEL parser, evaluation context, the root object and other predefined variables and other infrastructure will be created implicitly

EvaluationContext Interface

EvaluationContext acquisition interface defines attributes, methods, fields, and field type resolver converter. StandardEvaluationContext the implementation of which is used to manipulate objects reflection. To improve performance, he will java.lang.reflect its internal cache of Method, Field and Constructor instances.

StandardEvaluationContext class can be passed through evaluate root object constructor function, can also be specified by the evaluation method of the root object setRootObject (). You may be used setVariable () to set variables; use registerFunction (String name, Method method) to register the custom functions.

In StandardEvaluationContext, we can also register a custom constructor converter ConstructorResolvers, methods, and properties MethodResolvers converter converter PropertyAccessors to customize the expression of analytical methods.

By default, SpEL ConversionService is used to perform the conversion services. Which selects the appropriate adapter in accordance with the source type to the target type. Spring built a lot of converters:
Spring Expression Language (SpEL)

Built converter (part)

If the built-in translator can not meet the business needs, we can register custom converters.
When comprise generic expression, SpEL will attempt to convert the current value corresponding to the target type.

public class GenericConvertExample {
    public List<Integer> nums = new ArrayList();

    public static void main(String[] args) {

        GenericConvertExample example = new GenericConvertExample();
        example.nums.add(1);

        //创建表达式上下文
        StandardEvaluationContext context = new StandardEvaluationContext(example);
        //创建表达式解析器
        ExpressionParser parser = new SpelExpressionParser();

        String expression = "nums[0]";
        //自动将 2 转换为 Integer 类型
        parser.parseExpression(expression).setValue(context, 2);
        System.out.println("nums:" + example.nums);

        //抛出 ConverterNotFoundException
        try {
            parser.parseExpression(expression).setValue(context, true);
        } catch (EvaluationException e) {
            e.printStackTrace();s
        } catch (ParseException e) {
            e.printStackTrace();
        }

                //literal expressions 
        Expression exp = parser.parseExpression("'Hello World'");
        String msg1 = exp.getValue(String.class);
        System.out.println(msg1);

        //method invocation
        Expression exp2 = parser.parseExpression("'Hello World'.length()");  
        int msg2 = (Integer) exp2.getValue();
        System.out.println(msg2);

        //Mathematical operators
        Expression exp3 = parser.parseExpression("100 * 2");  
        int msg3 = (Integer) exp3.getValue();
        System.out.println(msg3);

        //create an item object
        Item item = new Item("yiibai", 100);
        //test EL with item object
        StandardEvaluationContext itemContext = new StandardEvaluationContext(item);

        //display the value of item.name property
        Expression exp4 = parser.parseExpression("name");
        String msg4 = exp4.getValue(itemContext, String.class);
        System.out.println(msg4);

        //test if item.name == 'yiibai'
        Expression exp5 = parser.parseExpression("name == 'yiibai'");
        boolean msg5 = exp5.getValue(itemContext, Boolean.class);
        System.out.println(msg5);

    }
}

Here's the definition of a List <Integer> class member variable, so we can pass directly to the integer value setValue () method. If the incoming object is a non-integer type, it will be thrown ConverterNotFoundException exception.

4 SpelCompiler compiler

By default, SpEL expression only when evaluated will be calculated expression, so the expression can be modified dynamically at runtime. But if the number of times an expression many be called repeatedly, then you must use
SpelCompiler compiler to ensure performance.

SpelCompiler expression compiler will be compiled into byte code, change the expression occurs only when running, will be recompiled.

SpelCompiler compiler suitable for high frequency is called and the expression change does not happen often scene.

//Spel 解析配置器
SpelParserConfiguration configuration=new SpelParserConfiguration
        (SpelCompilerMode.IMMEDIATE,CompilerExample.class.getClassLoader());

//解析器
SpelExpressionParser parser=new SpelExpressionParser(configuration);

//上下文
EvaluationContext context=new StandardEvaluationContext(new Account("Deniro"));

//表达式
String expression="getName()";

//解析表达式
SpelExpression spelExpression=parser.parseRaw(expression);

System.out.println(spelExpression.getValue(context));

We resolve to create a new Spel configuration mode by specifying the compiler and class loader.

Spel compiler parsing the configuration has three modes (SpelCompilerMode):

Compilation mode Explanation
OFF Compilation mode is not enabled (default). It can be set globally by the spring.expression.compiler.mode properties spring.properties.
MIXED In mixed mode, with time, the expression will automatically switch from the mode explains to compilation mode. That model used previously explained, when the number of calls reaches a certain threshold, using instead compilation mode.
IMMEDIATE Enable compilation mode. After calling the actual internal first time, you will really use the compiler mode.

This article presents some basic usage Spring expression parser, visit the official Spring express document , using the example of SpEL.

Reproduced in: https: //blog.51cto.com/ciyorecord/2409628

Guess you like

Origin blog.csdn.net/weixin_34187822/article/details/93098403