Skip to content

SpEL 表达式

1. SpEL 概述

Spring 表达式语言全称为 Spring Expression Language,缩写为“SpEL”,类似于 Struts2x 中使用的 OGNL 表达式语言,能在运行时构建复杂表达式、存取对象的属性、对象方法调用等等,并且能与 Spring 功能完美整合,如能用来配置 Bean 定义。

表达式语言给静态 Java 语言增加了动态功能。

SpEL 是单独模块,只依赖于 core 模块,不依赖于其他模块,可以单独使用。

表达式语言一般是用最简单的形式完成最主要的工作,减少我们的工作量,SpEL 支持如下表达式:

基本表达式:字面量表达式、关系,逻辑与算数运算表达式、字符串连接及截取表达式、三目运算及 Elivis 表达式、正则表达式、括号优先级表达式;

类相关表达式:类类型表达式、类实例化、instanceof 表达式、变量定义及引用、赋值表达式、自定义函数、对象属性存取及安全导航表达式、对象方法调用、Bean 引用;

集合相关表达式:内联 List、内联数组、集合,字典访问、列表,字典,数组修改、集合投影、集合选择;不支持多维内联数组初始化;不支持内联字典定义;

其他表达式:模板表达式。

提示

:SpEL 表达式中的关键字是不区分大小写的!

2. SpEL 基础

2.1 HelloWorld

一般的 Spring 项目都会包含支持 SpEL 的 Jar 包,不需要刻意修改依赖。

SpEL 在求表达式值时一般分为四步,其中第三步可选:首先构造一个解析器,其次解析器解析字符串表达式,在此构造上下文,最后根据上下文得到表达式运算后的值。

示例代码片段:

java
import org.junit.Test;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class SpelTest {
    @Test
    public void test1() {
        ExpressionParser parser = new SpelExpressionParser();
        Expression expression = parser.parseExpression("('Hello' + ' World').concat(#end)");
        EvaluationContext context = new StandardEvaluationContext();
        context.setVariable("end", "!");
        System.out.println(expression.getValue(context));
    }
}

执行以上代码,输出:

text
Hello World!

简单分析以上示例代码:

1)创建解析器:SpEL 使用 ExpressionParser 接口表示解析器,提供 SpelExpressionParser 默认实现;

2)解析表达式:使用 ExpressionParserparseExpression() 来解析相应的表达式为 Expression 对象;

3)构造上下文:准备比如变量定义等等表达式需要的上下文数据;

4)求值:通过 Expression 接口的 getValue() 方法根据上下文获得表达式值。

2.2 SpEL 原理及接口

SpEL 提供简单的接口从而简化用户使用,在介绍原理前让我们学习下几个概念:

  • 表达式:表达式是表达式语言的核心,所有表达式语言都是围绕表达式进行的,从我们角度来看就是“干什么”;

  • 解析器:用于将字符串表达式解析为表达式对象,从我们角度来看就是“谁来干”;

  • 上下文:表达式对象执行的环境,该环境可以定义变量、定义自定义函数、提供类型转换等等,从我们角度看就是“在哪干”;

  • 根对象及活动上下文对象:根对象是默认的活动上下文对象,表示当前表达式操作的对象,从我们角度看就是“对谁干”。

理解了这些概念后,让我们看下 SpEL 如何工作的呢,如图所示:

2.2.1 工作原理

首先定义表达式:“1+2”;

定义解析器 ExpressionParser 实现,SpEL 提供默认实现 SpelExpressionParserSpelExpressionParser 解析器内部使用 Tokenizer 类进行词法分析,即把字符串流分析为记号流,记号在 SpEL 使用 Token 类来表示;

有了记号流后,解析器便可根据记号流生成内部抽象语法树;在 SpEL中 语法树节点由 SpelNode 接口实现代表:如 OpPlus 表示加操作节点、IntLiteral 表示 int 型字面量节点;使用 SpelNodel 实现组成了抽象语法树;

对外提供 Expression 接口来简化表示抽象语法树,从而隐藏内部实现细节,并提供 getValue() 简单方法用于获取表达式值;SpEL 提供默认实现为 SpelExpression

定义表达式上下文对象(可选),SpEL 使用 EvaluationContext 接口表示上下文对象,用于设置根对象、自定义变量、自定义函数、类型转换器等,SpEL 提供默认实现 StandardEvaluationContext

使用表达式对象根据上下文对象(可选)求值(调用表达式对象的 getValue() 方法)获得结果。

2.2.2 主要接口

ExpressionParser 接口

表示解析器,默认实现是 org.springframework.expression.spel.standard 包中的 SpelExpressionParser 类,使用 parseExpression 方法将字符串表达式转换为 Expression 对象,对于 ParserContext 接口用于定义字符串表达式是不是模板,及模板开始与结束字符:

java
public interface ExpressionParser {
    Expression parseExpression(String expressionString) throws ParseException;
    Expression parseExpression(String expressionString, ParserContext context) throws ParseException;
}

默认传入的字符串表达式不是模板形式,如果需要定义表达式是模块,可以创建一个 ParserContext ,实现里面的接口方法,也可以直接使用 ParserContext 中预置的模板:

EvaluationContext 接口

表示上下文环境,默认实现是 org.springframework.expression.spel.support 包中的 StandardEvaluationContext 类,使用 setRootObject 方法来设置根对象,使用 setVariable 方法来注册自定义变量,使用 registerFunction 来注册自定义函数等等。

Expression 接口

表示表达式对象,默认实现是 org.springframework.expression.spel.standard 包中的 SpelExpression ,提供 getValue 方法用于获取表达式值,提供 setValue 方法用于设置对象值。

3. SpEL 语法

3.1 基本表达式

3.1.1 字面量表达式

SpEL 支持的字面量包括:字符串、数字类型(int、long、float、double)、布尔类型、null 类型。

java
//字符串
String str1 = parser.parseExpression("'Hello World!'").getValue(String.class);

//数字类型
int int1 = parser.parseExpression("1").getValue(Integer.class);
long long1 = parser.parseExpression("-1L").getValue(long.class);
float float1 = parser.parseExpression("1.1").getValue(Float.class);
double double1 = parser.parseExpression("1.1E+2").getValue(double.class);
int hex1 = parser.parseExpression("0xa").getValue(Integer.class);
long hex2 = parser.parseExpression("0xaL").getValue(long.class);

//布尔类型
boolean true1 = parser.parseExpression("true").getValue(boolean.class);
boolean false1 = parser.parseExpression("false").getValue(boolean.class);

//null类型
Object null1 = parser.parseExpression("null").getValue(Object.class);

3.1.2 算数运算表达式

SpEL支持加 (+)、减(-)、乘(*)、除(/)、求余(%)、幂(^) 运算。

java
//加减乘除
int result1 = parser.parseExpression("1+2-3*4/2").getValue(Integer.class);

//求余
int result2 = parser.parseExpression("4%3").getValue(Integer.class);

//幂运算
int result3 = parser.parseExpression("2^3").getValue(Integer.class);

SpEL 还提供求余(MOD)和除(DIV)这两个运算符,与“%”和“/”等价,不区分大小写。

3.1.3 关系表达式

支持 等于(==)、不等于(!=)、大于(>)、大于等于(>=)、小于(<)、小于等于(<=),区间(between)运算。

提示

区间 between 运算符右边操作数必须是列表类型,且只能包含 2 个元素。第一个元素为开始,第二个元素为结束,区间运算是包含边界值的,即 xxx>=list.get(0) && xxx<=list.get(1)

java
boolean v1 = parser.parseExpression("1 > 2").getValue(boolean.class);
boolean between1 = parser.parseExpression("1 between {1, 2}").getValue(boolean.class);

SpEL 同样提供了等价的“EQ” 、“NE”、 “GT”、“GE”、 “LT” 、“LE”来表示等于、不等于、大于、大于等于、小于、小于等于,不区分大小写。

3.1.4 逻辑表达式

支持 且(and 或者 &&)、或(or 或者 ||)、非(! 或 NOT)。

java
boolean result1 = parser.parseExpression("2>1 and (!true or !false)").getValue(boolean.class);
boolean result2 = parser.parseExpression("2>1 && (!true || !false)").getValue(boolean.class);

boolean result3 = parser.parseExpression("2>1 and (NOT true or NOT false)").getValue(boolean.class);
boolean result4 = parser.parseExpression("2>1 && (NOT true || NOT false)").getValue(boolean.class);

3.1.5 字符串连接及截取表达式

使用“+”进行字符串连接,使用“'String'[0][index]”来截取一个字符,目前只支持截取一个;

如“'Hello ' + 'World!'”得到“Hello World!”;而“'Hello World!'[0]”将返回“H”。

3.1.6 三目运算

三目运算符:表达式1?表达式2:表达式3,用于构造三目运算表达式

如“2 > 1 ? true : false”将返回 true;

3.1.7 Elivis运算符

Elivis 运算符:表达式1?:表达式2,从 Groovy 语言引入用于简化三目运算符的,当表达式 1 为非 null 时则返回表达式 1,当表达式 1 为 null 时则返回表达式 2,简化了三目运算符方式“表达式1?表达式1:表达式2”;

如“null?:false”将返回 false,而“true?:false”将返回 true;

3.1.8 正则表达式

使用 str matches regex,如“'123' matches '\d{3}'”将返回 true;

3.1.9 括号优先级表达式

使用 (表达式) 构造,括号里的具有高优先级。

3.2 类相关表达式

3.2.1 类类型表达式

使用 T(Type) 来表示 java.lang.Class 实例,“Type”必须是类全限定名,“java.lang”包除外,即该包下的类可以不指定包名;使用类类型表达式还可以进行访问类静态方法及类静态字段。

具体使用方法如下:

java
@Test
public void testClassTypeExpression() {
    ExpressionParser parser = new SpelExpressionParser();
    //java.lang包类访问
    Class<String> result1 = parser.parseExpression("T(String)").getValue(Class.class);
    System.out.println(result1);

    //其他包类访问
    String expression2 = "T(com.javacode2018.spel.SpelTest)";
    Class<SpelTest> value = parser.parseExpression(expression2).getValue(Class.class);
    System.out.println(value == SpelTest.class);

    //类静态字段访问
    int result3 = parser.parseExpression("T(Integer).MAX_VALUE").getValue(int.class);
    System.out.println(result3 == Integer.MAX_VALUE);

    //类静态方法调用
    int result4 = parser.parseExpression("T(Integer).parseInt('1')").getValue(int.class);
    System.out.println(result4);
}

3.2.2 类实例化

类实例化同样使用 java 关键字“new”,类名必须是全限定名,但 java.lang 包内的类型除外,如 String、Integer。

java
@Test
public void testConstructorExpression() {
    ExpressionParser parser = new SpelExpressionParser();
    String result1 = parser.parseExpression("new String('路人甲java')").getValue(String.class);
    System.out.println(result1);

    Date result2 = parser.parseExpression("new java.util.Date()").getValue(Date.class);
    System.out.println(result2);
}

3.2.3 instanceof 表达式

SpEL 支持 instanceof 运算符,跟 Java 内使用同义;

java
@Test
public void testInstanceOfExpression() {
    ExpressionParser parser = new SpelExpressionParser();
    Boolean value = parser.parseExpression("'路人甲' instanceof T(String)").getValue(Boolean.class);
    System.out.println(value);
}

3.2.4 变量定义及引用

变量定义通过 EvaluationContext 接口的 setVariable(variableName, value) 方法定义;在表达式中使用 #variableName 引用;除了引用自定义变量,SpEL 还允许引用根对象及当前上下文对象,使用 #root 引用根对象,使用 #this 引用当前上下文对象,#this 即根对象;

java
@Test
public void testVariableExpression() {
    ExpressionParser parser = new SpelExpressionParser();
    EvaluationContext context = new StandardEvaluationContext();
    context.setVariable("name", "路人甲java");
    context.setVariable("lesson", "Spring系列");

    //获取name变量,lesson变量
    String name = parser.parseExpression("#name").getValue(context, String.class);
    System.out.println(name);
    String lesson = parser.parseExpression("#lesson").getValue(context, String.class);
    System.out.println(lesson);

    //StandardEvaluationContext构造器传入root对象,可以通过#root来访问root对象
    context = new StandardEvaluationContext("我是root对象");
    String rootObj = parser.parseExpression("#root").getValue(context, String.class);
    System.out.println(rootObj);

    //#this用来访问当前上线文中的对象
    String thisObj = parser.parseExpression("#this").getValue(context, String.class);
    System.out.println(thisObj);
}

3.2.5 自定义函数

目前只支持类静态方法注册为自定义函数;SpEL 使用 StandardEvaluationContextregisterFunction() 方法进行注册自定义函数,其实完全可以使用 setVariable() 代替,两者其实本质是一样的;

java
@Test
public void testFunctionExpression() throws SecurityException, NoSuchMethodException {
    //定义2个函数,registerFunction和setVariable都可以,不过从语义上面来看用registerFunction更恰当
    StandardEvaluationContext context = new StandardEvaluationContext();
    Method parseInt = Integer.class.getDeclaredMethod("parseInt", String.class);
    context.registerFunction("parseInt1", parseInt);
    context.setVariable("parseInt2", parseInt);

    ExpressionParser parser = new SpelExpressionParser();
    System.out.println(parser.parseExpression("#parseInt1('3')").getValue(context, int.class));
    System.out.println(parser.parseExpression("#parseInt2('3')").getValue(context, int.class));

    String expression1 = "#parseInt1('3') == #parseInt2('3')";
    boolean result1 = parser.parseExpression(expression1).getValue(context, boolean.class);
    System.out.println(result1);
}

3.2.6 表达式赋值

使用 Expression#setValue 方法可以给表达式赋值。

java
@Test
public void testAssignExpression1() {
    {
        //user为root对象
        ExpressionParser parser = new SpelExpressionParser();
        EvaluationContext context = new StandardEvaluationContext(user);
        parser.parseExpression("#root.name").setValue(context, "路人甲java");
        System.out.println(parser.parseExpression("#root").getValue(context, user.getClass()));
    }
    {
        //user为变量
        ExpressionParser parser = new SpelExpressionParser();
        EvaluationContext context = new StandardEvaluationContext();
        context.setVariable("user", user);
        parser.parseExpression("#user.name").setValue(context, "路人甲java");
        System.out.println(parser.parseExpression("#user").getValue(context, user.getClass()));
    }
}

3.2.7 对象属性存取及安全导航表达式

对象属性获取非常简单,即使用如“a.property.property”这种点缀式获取,SpEL 对于属性名首字母是不区分大小写的;SpEL 还引入了 Groovy 语言中的安全导航运算符“(对象|属性)?.属性”,用来避免“?.”前边的表达式为 null 时抛出空指针异常,而是返回 null;修改对象属性值则可以通过赋值表达式或 Expression 接口的 setValue 方法修改。

java
@Test
public void test5() {
    User user = new User();
    EvaluationContext context = new StandardEvaluationContext();
    context.setVariable("user", user);

    ExpressionParser parser = new SpelExpressionParser();
    //使用.符号,访问user.car.name会报错,原因:user.car为空
    try {
        System.out.println(parser.parseExpression("#user.car.name").getValue(context, String.class));
    } catch (EvaluationException | ParseException e) {
        System.out.println("出错了:" + e.getMessage());
    }
    //使用安全访问符号?.,可以规避null错误
    System.out.println(parser.parseExpression("#user?.car?.name").getValue(context, String.class));

    Car car = new Car();
    car.setName("保时捷");
    user.setCar(car);

    System.out.println(parser.parseExpression("#user?.car?.toString()").getValue(context, String.class));
}

3.2.8 对象方法调用

对象方法调用更简单,跟 Java 语法一样;如“'haha'.substring(2,4)”将返回“ha”;而对于根对象可以直接调用方法;

3.2.9 Bean 引用

SpEL 支持使用“@”符号来引用 Bean,在引用 Bean 时需要使用 BeanResolver 接口实现来查找 Bean,Spring 提供 BeanFactoryResolver 实现。

java
@Test
public void test6() {
    DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
    User user = new User();
    Car car = new Car();
    car.setName("保时捷");
    user.setCar(car);
    factory.registerSingleton("user", user);

    StandardEvaluationContext context = new StandardEvaluationContext();
    context.setBeanResolver(new BeanFactoryResolver(factory));

    ExpressionParser parser = new SpelExpressionParser();
    User userBean = parser.parseExpression("@user").getValue(context, User.class);
    System.out.println(userBean);
    System.out.println(userBean == factory.getBean("user"));
}

3.3 集合相关表达式

3.3.1 内联 List

从 Spring3.0.4 开始支持内联 List,使用 {表达式,……} 定义内联 List,如“{1,2,3}”将返回一个整型的 ArrayList,而“{}”将返回空的 List,对于字面量表达式列表,SpEL 会使用 java.util.Collections.unmodifiableList 方法将列表设置为不可修改。

java
@Test
public void test7() {
    ExpressionParser parser = new SpelExpressionParser();
    //将返回不可修改的空List
    List<Integer> result2 = parser.parseExpression("{}").getValue(List.class);
    //对于字面量列表也将返回不可修改的List
    List<Integer> result1 = parser.parseExpression("{1,2,3}").getValue(List.class);
    Assert.assertEquals(new Integer(1), result1.get(0));
    try {
        result1.set(0, 2);
    } catch (Exception e) {
        e.printStackTrace();
    }
    //对于列表中只要有一个不是字面量表达式,将只返回原始List,
    //不会进行不可修改处理
    String expression3 = "{{1+2,2+4},{3,4+4}}";
    List<List<Integer>> result3 = parser.parseExpression(expression3).getValue(List.class);
    result3.get(0).set(0, 1);
    System.out.println(result3);
    //声明二维数组并初始化
    int[] result4 = parser.parseExpression("new int[2]{1,2}").getValue(int[].class);
    System.out.println(result4[1]);
    //定义一维数组并初始化
    int[] result5 = parser.parseExpression("new int[1]").getValue(int[].class);
    System.out.println(result5[0]);
}

3.3.2 内联数组

和 Java 数组定义类似,只是在定义时进行多维数组初始化。

java
int[][][] result4 = parser.parseExpression("new int[1][2][3]{{1}{2}{3}}").getValue(int[][][].class);

3.3.3 集合,字典元素访问

SpEL 目前支持所有集合类型和字典类型的元素访问,使用“集合[索引]”访问集合元素,使用“map[key]”访问字典元素;

java
//SpEL内联List访问
int result1 = parser.parseExpression("{1,2,3}[0]").getValue(int.class);

//SpEL目前支持所有集合类型的访问
Collection<Integer> collection = new HashSet<Integer>();
collection.add(1);
collection.add(2);

EvaluationContext context2 = new StandardEvaluationContext();
context2.setVariable("collection", collection);
int result2 = parser.parseExpression("#collection[1]").getValue(context2, int.class);


//SpEL对Map字典元素访问的支持
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("a", 1);

EvaluationContext context3 = new StandardEvaluationContext();
context3.setVariable("map", map);
int result3 = parser.parseExpression("#map['a']").getValue(context3, int.class);

3.3.4 列表,字典,数组元素修改

可以使用赋值表达式或Expression接口的setValue方法修改;

java
@Test
public void test8() {
    ExpressionParser parser = new SpelExpressionParser();

    //修改list元素值
    List<Integer> list = new ArrayList<Integer>();
    list.add(1);
    list.add(2);

    EvaluationContext context1 = new StandardEvaluationContext();
    context1.setVariable("collection", list);
    parser.parseExpression("#collection[1]").setValue(context1, 4);
    int result1 = parser.parseExpression("#collection[1]").getValue(context1, int.class);
    System.out.println(result1);

    //修改map元素值
    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("a", 1);
    EvaluationContext context2 = new StandardEvaluationContext();
    context2.setVariable("map", map);
    parser.parseExpression("#map['a']").setValue(context2, 4);
    Integer result2 = parser.parseExpression("#map['a']").getValue(context2, int.class);
    System.out.println(result2);
}

3.3.5 集合投影

在 SQL 中投影指从表中选择出列,而在 SpEL 指根据集合中的元素中通过选择来构造另一个集合,该集合和原集合具有相同数量的元素;SpEL 使用“(list|map).![投影表达式]”来进行投影运算:

java
@Test
public void test9() {
    ExpressionParser parser = new SpelExpressionParser();

    //1.测试集合或数组
    List<Integer> list = new ArrayList<Integer>();
    list.add(4);
    list.add(5);
    EvaluationContext context1 = new StandardEvaluationContext();
    context1.setVariable("list", list);
    Collection<Integer> result1 = parser.parseExpression("#list.![#this+1]").getValue(context1, Collection.class);
    result1.forEach(System.out::println);

    System.out.println("------------");
    //2.测试字典
    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("a", 1);
    map.put("b", 2);
    EvaluationContext context2 = new StandardEvaluationContext();
    context2.setVariable("map", map);
    List<Integer> result2 = parser.parseExpression("#map.![value+1]").getValue(context2, List.class);
    result2.forEach(System.out::println);
}

对于集合或数组使用如上表达式进行投影运算,其中投影表达式中“#this”代表每个集合或数组元素,可以使用比如“#this.property”来获取集合元素的属性,其中“#this”可以省略。

Map 投影最终只能得到 List 结果,如上所示,对于投影表达式中的“#this”将是 Map.Entry,所以可以使用“value”来获取值,使用“key”来获取键。

3.3.6 集合选择

在 SQL 中指使用 select 进行选择行数据,而在 SpEL 指根据原集合通过条件表达式选择出满足条件的元素并构造为新的集合,SpEL 使用“(list|map).?[选择表达式]”,其中选择表达式结果必须是 boolean 类型,如果 true 则选择的元素将添加到新集合中,false 将不添加到新集合中。

java
@Test
public void test10() {
    ExpressionParser parser = new SpelExpressionParser();

    //1.测试集合或数组
    List<Integer> list = new ArrayList<Integer>();
    list.add(1);
    list.add(4);
    list.add(5);
    list.add(7);
    EvaluationContext context1 = new StandardEvaluationContext();
    context1.setVariable("list", list);
    Collection<Integer> result1 = parser.parseExpression("#list.?[#this>4]").getValue(context1, Collection.class);
    result1.forEach(System.out::println);

    System.out.println("------------");
}

对于集合或数组选择,如“#collection.?[#this>4]”将选择出集合元素值大于4的所有元素。选择表达式必须返回布尔类型,使用“#this”表示当前元素。

java
//2.测试字典
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
EvaluationContext context2 = new StandardEvaluationContext();
context2.setVariable("map", map);
Map<String, Integer> result2 = parser.parseExpression("#map.?[key!='a']").getValue(context2, Map.class);
result2.forEach((key, value) -> {
    System.out.println(key + ":" + value);
});
System.out.println("------------");
List<Integer> result3 = parser.parseExpression("#map.?[key!='a'].![value+1]").getValue(context2, List.class);
result3.forEach(System.out::println);

对于字典选择,如“#map.?[#this.key != 'a']”将选择键值不等于”a”的,其中选择表达式中“#this”是Map.Entry类型,而最终结果还是Map,这点和投影不同;集合选择和投影可以一起使用,如“#map.?[key != 'a'].![value+1]”将首先选择键值不等于”a”的,然后在选出的Map中再进行“value+1”的投影。

3.4 表达式模板

模板表达式就是由字面量与一个或多个表达式块组成。每个表达式块由“前缀+表达式+后缀”形式组成,如“${1+2}”即表达式块。在前边我们已经介绍了使用 ParserContext 接口实现来定义表达式是否是模板及前缀和后缀定义。在此就不多介绍了,如“Error ${#v0} ${#v1}”表达式表示由字面量“Error ”、模板表达式“#v0”、模板表达式“#v1”组成,其中 v0 和 v1 表示自定义变量,需要在上下文定义。

解析表达式的时候需要指定模板,模板通过 ParserContext 接口来定义

java
public interface ParserContext {
    //是否是模板
    boolean isTemplate();
    //模板表达式前缀
    String getExpressionPrefix();
    //模板表达式后缀
    String getExpressionSuffix();
}
java
@Test
public void test11() {
    //创建解析器
    SpelExpressionParser parser = new SpelExpressionParser();
    //创建解析器上下文
    ParserContext context = new TemplateParserContext("%{", "}");
    Expression expression = parser.parseExpression("你好:%{#name},我们正在学习:%{#lesson}", context);

    //创建表达式计算上下文
    EvaluationContext evaluationContext = new StandardEvaluationContext();
    evaluationContext.setVariable("name", "路人甲java");
    evaluationContext.setVariable("lesson", "spring高手系列!");
    //获取值
    String value = expression.getValue(evaluationContext, String.class);
    System.out.println(value);
}

#4. 在 Bean 定义中使用 SpEL 表达式

4.1 xml 风格的配置

SpEL 支持在 Bean 定义时注入,默认使用“#{SpEL表达式}”表示,其中“#root”根对象默认可以认为是 ApplicationContext,只有 ApplicationContext 实现默认支持 SpEL,获取根对象属性其实是获取容器中的 Bean。

xml
<bean id="world" class="java.lang.String">
    <constructor-arg value="#{' World!'}"/>
</bean>

<bean id="hello1" class="java.lang.String">
    <constructor-arg value="#{'Hello'}#{world}"/>
</bean>

<bean id="hello2" class="java.lang.String">
    <constructor-arg value="#{'Hello' + world}"/>
</bean>

<bean id="hello3" class="java.lang.String">
    <constructor-arg value="#{'Hello' + @world}"/>
</bean>

模板默认以前缀“#{”开头,以后缀“}”结尾,且不允许嵌套,如“#{'Hello'#{world}}”错误,如“#{'Hello' + world}”中“world”默认解析为Bean。当然可以使用“@bean”引用了。

4.2 注解风格的配置

基于注解风格的 SpEL 配置也非常简单,使用 @Value 注解来指定 SpEL 表达式,该注解可以放到字段、方法及方法参数上。

测试 Bean 类如下,使用 @Value 来指定 SpEL 表达式:

java
public class SpELBean {
    @Value("#{'Hello' + world}")
    private String value;
}

4.3 在 Bean 定义中 SpEL 的问题

如果有人问“#{我不是SpEL表达式}”不是SpEL表达式,而是公司内部的模板,想换个前缀和后缀该如何实现呢?

我们使用 BeanFactoryPostProcessor 接口提供 postProcessBeanFactory 回调方法,它是在 IoC 容器创建好但还未进行任何 Bean 初始化时被 ApplicationContext 实现调用,因此在这个阶段把 SpEL 前缀及后缀修改掉是安全的,具体代码如下:

java
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanExpressionResolver;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.expression.StandardBeanExpressionResolver;
import org.springframework.stereotype.Component;

@Component
public class SpelBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        BeanExpressionResolver beanExpressionResolver = beanFactory.getBeanExpressionResolver();
        if (beanExpressionResolver instanceof StandardBeanExpressionResolver) {
            StandardBeanExpressionResolver resolver = (StandardBeanExpressionResolver) beanExpressionResolver;
            resolver.setExpressionPrefix("%{");
            resolver.setExpressionSuffix("}");
        }
    }
}