跳到主要内容

Value Expressions 基础

QWen Flash 中英对照 Value Expressions Fundamentals

Value Expressions 是 Spring Expression Language (SpEL) 与 Property Placeholder Resolution 的组合。它们将编程表达式的强大求值能力与属性占位符解析的简洁性结合起来,从而通过属性占位符解析从 Environment 中获取配置属性等值。

Expressions 应由 trusted input(例如 annotation value)定义,而不应由 user input 决定。

范围​

Value Expressions 用于跨注解的上下文。Spring Data 在两个主要上下文中提供 Value Expression 求值:

  • 映射模型注解:例如 @Document、@Field、@Value 以及其他注解,这些注解位于自带映射模型和相应 Entity Reader 的 Spring Data 模块中,例如 MongoDB、Elasticsearch、Cassandra、Neo4j。基于提供自身映射模型的库(JPA、LDAP)构建的模块,不支持在映射注解中使用 Value Expressions。

    以下代码演示如何在映射模型注解的上下文中使用表达式。

    示例 1:@Document 注解用法

    @Document("orders-#{tenantService.getOrderCollection()}-${tenant-config.suffix}")
    class Order {
    // …
    }
  • 仓储查询方法:主要通过 @Query 实现。

    以下代码演示如何在仓储查询方法的上下文中使用表达式。

    示例 2:@Query 注解用法

    class OrderRepository extends Repository<Order, String> {

    @Query("select u from User u where u.tenant = ?${spring.application.name:unknown} and u.firstname like %?#{escape([0])}% escape ?#{escapeCharacter()}")
    List<Order> findContainingEscaped(String namePart);
    }
备注

请查阅你的模块文档,以确定实际的参数按名称/按索引绑定语法。通常,表达式前缀为 :#{…}/:${…} 或 ?#{…}/?${…}。

表达式语法​

Value Expressions 可以由一个单独的 SpEL Expression、一个 Property Placeholder,或者一个混合了各种表达式(包括 literals)的 composite expression 定义。

示例 3. 表达式示例

#{tenantService.getOrderCollection()}                          // <1>
#{(1+1) + '-hello-world'} // <2>
${tenant-config.suffix} // <3>
orders-${tenant-config.suffix} // <4>
#{tenantService.getOrderCollection()}-${tenant-config.suffix} // <5>
  • 使用单个 SpEL 表达式的 Value Expression。

  • 使用静态 SpEL 表达式的 Value Expression,计算结果为 2-hello-world。

  • 使用单个 Property Placeholder 的 Value Expression。

  • 由字面量 orders- 和 Property Placeholder ${tenant-config.suffix} 组成的复合表达式。

  • 使用 SpEL、Property Placeholders 和字面量的复合表达式。

备注

使用 value expressions 为代码引入了大量灵活性。这样做需要在每次使用时对 expression 进行求值,因此 value expressions 的求值会对 performance profile 产生影响。

Spring Expression Language (SpEL) 和 Property Placeholder Resolution 详细说明了 SpEL 和 Property Placeholders 的语法与能力。

解析与求值​

Value Expressions 由 ValueExpressionParser API 解析。ValueExpression 实例是线程安全的,可以缓存以供后续使用,避免重复解析。

以下示例展示了 Value Expression API 的用法:

ValueParserConfiguration configuration = SpelExpressionParser::new;
ValueEvaluationContext context = ValueEvaluationContext.of(environment, evaluationContext);

ValueExpressionParser parser = ValueExpressionParser.create(configuration);
ValueExpression expression = parser.parse("Hello, World");
Object result = expression.evaluate(context);

SpEL 表达式​

SpEL Expressions 遵循 Template 风格,其中表达式需要包含在 #{…} 格式中。表达式使用由 EvaluationContextProvider 提供的 EvaluationContext 进行求值。上下文本身是一个强大的 StandardEvaluationContext,允许进行广泛的操作、访问静态类型和上下文扩展。

备注

请确保仅解析和评估来自可信来源(如 annotations)的表达式。接受用户提供的表达式可能会创建入口路径,从而利用应用程序上下文和您的系统,导致潜在的安全漏洞。

扩展求值上下文​

EvaluationContextProvider 及其响应式变体 ReactiveEvaluationContextProvider 提供对 EvaluationContext 的访问。ExtensionAwareEvaluationContextProvider 及其响应式变体 ReactiveExtensionAwareEvaluationContextProvider 是默认实现,它们从应用上下文中确定上下文扩展,具体为 ListableBeanFactory。

扩展实现 EvaluationContextExtension 或 ReactiveEvaluationContextExtension,用于使用以下内容填充 EvaluationContext:根对象、命名属性和函数(顶层方法)。

以下示例展示了一个上下文扩展,它提供了根对象、属性、函数和别名函数。

@Component
public class MyExtension implements EvaluationContextExtension {

@Override
public String getExtensionId() {
return "my-extension";
}

@Override
public Object getRootObject() {
return new CustomExtensionRootObject();
}

@Override
public Map<String, Object> getProperties() {

Map<String, Object> properties = new HashMap<>();

properties.put("key", "Hello");

return properties;
}

@Override
public Map<String, Function> getFunctions() {

Map<String, Function> functions = new HashMap<>();

try {
functions.put("aliasedMethod", new Function(getClass().getMethod("extensionMethod")));
return functions;
} catch (Exception o_O) {
throw new RuntimeException(o_O);
}
}

public static String extensionMethod() {
return "Hello World";
}

public static int add(int i1, int i2) {
return i1 + i2;
}

}

public class CustomExtensionRootObject {

public boolean rootObjectInstanceMethod() {
return true;
}

}

一旦注册了上述扩展,就可以使用其导出的方法、属性和根对象来评估 SpEL 表达式:

示例 4. 表达式求值示例

#{add(1, 2)}                                             // <1>
#{extensionMethod()} // <2>
#{aliasedMethod()} // <3>
#{key} // <4>
#{rootObjectInstanceMethod()} // <5>
  • 调用由 MyExtension 声明的 add 方法,结果为 3,因为该方法将两个数字参数相加并返回其和。

  • 调用由 MyExtension 声明的 extensionMethod 方法,结果为 Hello World。

  • 调用 aliasedMethod 方法。该方法以函数形式暴露,并重定向到由 MyExtension 声明的 extensionMethod 方法,结果为 Hello World。

  • 评估 key 属性,结果为 Hello。

  • 在根对象实例 CustomExtensionRootObject 上调用 rootObjectInstanceMethod 方法。

你可以在 SecurityEvaluationContextExtension 中了解真实场景下的上下文扩展。

属性占位符​

形如 ${…} 的 property placeholders 通常引用由 PropertySource 通过 Environment 提供的 properties。properties 可用于针对 system properties、application configuration files、environment configuration 或 secret management systems 提供的 property sources 进行解析。你可以在 Spring Framework 关于 @Value 使用的文档 中查看 property placeholders 的更多细节。