Spring Learns Notes SpEL Expression Language (Spring)


Spring Expression Language (SpEL) is a powerful expression language that supports runtime queries and manipulation of object diagrams. Expression languages generally do the most important work in the simplest form to reduce the workload.

Java has many expression languages available, such as JSP EL, OGNL, MVEL, and JBoss EL. SpEL syntax is similar to JSP EL, and functions like OGNL in Struts2. It can build complex expressions at runtime, access object graph properties, call object methods, and so on. It also integrates perfectly with Spring functions, such as SpEL, which can be used to configure Bean definitions.

SpEL is not directly related to Spring and can be used independently. SpEL expressions were created to provide the Spring community with a well-supported expression language for all products in the Spring family. That is, SpEL is a technology-independent API that can integrate other expression languages.

SpEL provides the following interfaces and classes:

  • Expression interface: This interface is responsible for evaluating expression strings
  • ExpressionParser interface: This interface is responsible for parsing strings
  • EvaluationContext interface: This interface is responsible for defining the context

SpEL supports the following expressions:
1. Basic Expressions
Literal expression, relation, logical and arithmetic expression, string connection and truncation expression, trinomial expression, regular expression, parentheses priority expression;
2. Class-related expressions
Class type expression, class instantiation, instanceof expression, variable definition and reference, assignment expression, custom function, object property access and safe navigation expression, object method call, Bean reference;
3. Set-related expressions
Inline List, Inline Array, Collection, Dictionary Access, List, Dictionary, Array Modification, Collection Projection, Collection Selection; Multidimensional inline array initialization is not supported; Inline dictionary definitions are not supported;
4. Other expressions
Template expression.

Note: Keywords in SpEL expressions are case insensitive.

Example

Example 1

The following uses SpEL to output a simple string "Hello, Programming Help".

package net.biancheng;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
public class Test {
    public static void main(String[] args) {
        // Construct Parser
        ExpressionParser parser = new SpelExpressionParser();
        // Parser parses string expressions
        Expression exp = parser.parseExpression("'Hello,Programming Help'");
        // Get the value of the expression
        String message = (String) exp.getValue();
        System.out.println(message);
        // OR
        // System.out.println (parser.parseExpression (''Hello, Programming Help'). getValue());
    }
}

The output is as follows.

Hello,Programming Help

SpEL can also call methods, access properties, and call constructors.

Example 2

Use SpEL to call the concat() method with the following code.

package net.biancheng;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
public class Test {
    public static void main(String[] args) {
        ExpressionParser parser = new SpelExpressionParser();
        Expression exp = parser.parseExpression("'Welcome,Programming Help'.concat('!')");
        String message = (String) exp.getValue();
        System.out.println(message);
    }
}

The output is as follows.

Welcome,Programming Help!

Example 3

Use SpEL to call String's property bytes and convert the string to a byte array, as shown below.

package net.biancheng;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
public class Test {
    public static void main(String[] args) {
        ExpressionParser parser = new SpelExpressionParser();
        Expression exp = parser.parseExpression("'Hello Programming Help'.bytes");
        byte[] bytes = (byte[]) exp.getValue();
        for (int i = 0; i < bytes.length; i++) {
            System.out.print(bytes[i] + " ");
        }
    }
}

The output is as follows.

72 101 108 108 111 32 -79 -32 -77 -52 -80 -17 

Example 4

SpEL also supports the use of nested attributes, which are converted to bytes to get the length in the following code.

package net.biancheng;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
public class Test {
    public static void main(String[] args) {
        ExpressionParser parser = new SpelExpressionParser();
        Expression exp = parser.parseExpression("'Hello Programming Help'.bytes.length");
        int length = (Integer) exp.getValue();
        System.out.println(length);
    }
}

The output is as follows.

12

Example 5

String constructors can be called instead of using string text, which is converted to uppercase letters in the following code.

package net.biancheng;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
public class Test {
    public static void main(String[] args) {
        ExpressionParser parser = new SpelExpressionParser();
        Expression exp = parser.parseExpression("new String('hello bianchengbang').toUpperCase()");
        String message = exp.getValue(String.class);
        System.out.println(message);
        // OR
        // System.out.println(parser.parseExpression("'hello
        // bianchengbang'.toUpperCase()").getValue());
    }
}

The output is as follows.

HELLO BIANCHENGBANG

SpEL support for Bean definitions

SpEL expressions can be used with XML or annotation-based configuration metadata, starting with #{and ending with}, such as #{'Hello'}.

1. XML-based configuration

The following expressions can be used to set parameter values for attributes or constructors.

<bean id="number" class="net.biancheng.Number">
    <property name="randomNumber" value="#{T(java.lang.Math).random() * 100.0}"/>
</bean>

Other Bean properties can also be referenced by name, such as the code below.

<bean id="shapeGuess" class="net.biancheng.ShapeGuess">
    <property name="shapSeed" value="#{number.randomNumber}"/>
</bean>

2. Annotation-based configuration

The @Value annotation can be placed on fields, methods, and constructor parameters to specify default values.

The following is an example of setting a default value for a field variable.

public static class FieldValueTestBean
    @value("#{ systemProperties[ 'user.region'] }")
    private String defaultLocale;
    public void setDefaultLocale (String defaultLocale) {
        this.defaultLocale = defaultLocale;
    }
    public string getDefaultLocale() {
        return this.defaultLocale;
    }
}

Operators in SpEL

Operators such as arithmetic, relational, and logical operators can be used in SpEL.

Example 6

package net.biancheng;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
public class Test {
    public static void main(String[] args) {
        ExpressionParser parser = new SpelExpressionParser();
        // Arithmetic Operators
        System.out.println(parser.parseExpression("'Hello SPEL'+'!'").getValue());
        System.out.println(parser.parseExpression("10 * 10/2").getValue());
        System.out.println(parser.parseExpression("'Today is:'+ new java.util.Date()").getValue());
        // Logical operators
        System.out.println(parser.parseExpression("true and true").getValue());
        // Relational Operators
        System.out.println(parser.parseExpression("'sonoo'.length()==5").getValue());
    }
}

The output is

Hello SPEL!
50
 Today is: Fri Feb 05 09:31:46 CST 2021
true
true

Variables in SpEL

In SpEL, we can define variables and use them in methods. The StandardEvaluationContext class is required to define variables.

Example 7

The Calculation class code is as follows.

package net.biancheng;
public class Calculation {
    private int number;
    public int getNumber() {
        return number;
    }
    public void setNumber(int number) {
        this.number = number;
    }
    public int cube() {
        return number * number * number;
    }
}

The Test class code is as follows.

package net.biancheng;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
public class Test {
    public static void main(String[] args) {
        Calculation calculation = new Calculation();
        StandardEvaluationContext context = new StandardEvaluationContext(calculation);
        ExpressionParser parser = new SpelExpressionParser();
        parser.parseExpression("number").setValue(context, "5");
        System.out.println(calculation.cube());
    }
}

Tags: Java Spring Back-end

Posted on Thu, 21 Oct 2021 14:59:12 -0400 by PFMaBiSmAd