Spring表达式实现变量替换

SpEL简介与功能特性

Spring表达式语言(简称SpEL)是一个支持查询并在运行时操纵一个对象图的功能强大的表达式语言。SpEL语言的语法类似于统一EL,但提供了更多的功能,最主要的是显式方法调用和基本字符串模板函数。

参考:https://www.cnblogs.com/best/p/5748105.html

在Maven 项目添加依赖

pom.xml如下所示:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.SpEl</groupId>
    <artifactId>Spring053</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>Spring053</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>4.3.0.RELEASE</spring.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
            <version>4.10</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.9</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.2.4</version>
        </dependency>
    </dependencies>
</project>

变量与赋值

变量:变量可以在表达式中使用语法#’变量名’引用
ExpressionParser ep= new SpelExpressionParser();
//创建上下文变量
EvaluationContext ctx = new StandardEvaluationContext();
ctx.setVariable(“name”, “Hello”);
System.out.println(ep.parseExpression("#name").getValue(ctx));

输出:Hello
赋值:属性设置是通过使用赋值运算符。这通常是在调用setValue中执行但也可以在调用getValue内,也可通过”#varName=value”的形式给变量赋值。
System.out.println(ep.parseExpression("#name='Ryo'").getValue(ctx));

输出:Ryo

实现一个变量替换的例子

给两个变量alarmTime、location赋值,最后用一个含有其它字符串的表达式中,实际输出变量的真实值

public class SpelTest {

    public static void main(String[] args) {
        ExpressionParser ep = new SpelExpressionParser();
        // 创建上下文变量
        EvaluationContext ctx = new StandardEvaluationContext();
        ctx.setVariable("alarmTime", "2018-09-26 13:00:00");
        ctx.setVariable("location", "二楼201机房");
        System.out.println(ep.parseExpression("告警发生时间 #{#alarmTime},位置是在#{#location}", new TemplateParserContext()).getValue(ctx));
    }
}

运行main方法,结果输出告警发生时间 2018-09-26 13:00:00,位置是在二楼201机房
 

猜你喜欢

转载自blog.csdn.net/zhigang0529/article/details/83178167