Expression Templating
表达式模板允许将文字内容与一个或多个评估块混合。每个评估块都用你可以定义的前缀和后缀字符进行分隔。一个常见选择是使用 #{ }
作为分隔符,如下例所示:
Expression templates allow mixing literal text with one or more evaluation blocks.
Each evaluation block is delimited with prefix and suffix characters that you can
define. A common choice is to use #{ }
as the delimiters, as the following example
shows:
-
Java
-
Kotlin
String randomPhrase = parser.parseExpression(
"random number is #{T(java.lang.Math).random()}",
new TemplateParserContext()).getValue(String.class);
// evaluates to "random number is 0.7038186818312008"
val randomPhrase = parser.parseExpression(
"random number is #{T(java.lang.Math).random()}",
TemplateParserContext()).getValue(String::class.java)
// evaluates to "random number is 0.7038186818312008"
表达式通过将字面文本“随机数是”与求解 {} 分隔符内表达式的结果(本例中,是调用 random() 方法的结果)连接在一起进行求值。 parseExpression() 方法的第二个参数是 ParserContext 类型。 ParserContext 接口用于影响表达式的解析方式,以支持表达式模板处理功能。 前面示例中使用的 TemplateParserContext 位于 org.springframework.expression.common 包中,并且是 ParserContext 的实现,它默认将前缀和后缀分别配置为 #{ 和 }。
The string is evaluated by concatenating the literal text ’random number is '` with the
result of evaluating the expression inside the { }
delimiters (in this case, the
result of calling that random()
method). The second argument to the parseExpression()
method is of the type ParserContext
. The ParserContext
interface is used to influence
how the expression is parsed in order to support the expression templating functionality.
The TemplateParserContext
used in the previous example resides in the
org.springframework.expression.common
package and is an implementation of the
ParserContext
which by default configures the prefix and suffix to {
and }
,
respectively.