第 31 章 SpEL
概述
Spring Expression Language (SpEL) 是一个带有 Spring 3 的对象图形导航语言,可用于在路由中构建 predicates 和表达式。SpEL 的显著功能是您可以从 registry 访问 Bean 的简单功能。
语法
SpEL 表达式必须使用占位符语法 #{SpelExpression},以便它们可以嵌入到纯文本字符串中(换句话说,SpEL 启用了表达式模板)。
SpEL 还可使用 @BeanID语法在注册表中查找 Bean (通常是 Spring 注册表)。例如,使用 ID、headerUtils 和方法 count () (计数当前消息中的标头数)指定 bean,您可以在 SpEL predicate 中使用 headerUtils bean,如下所示:
#{@headerUtils.count > 4}添加 SpEL 软件包
要在路由中使用 SpEL,需要在项目中添加对 camel-spring 的依赖,如 例 31.1 “添加 camel-spring 依赖项” 所示。
例 31.1. 添加 camel-spring 依赖项
<!-- Maven POM File -->
<properties>
<camel-version>2.23.2.fuse-790054-redhat-00001</camel-version>
...
</properties>
<dependencies>
...
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-spring</artifactId>
<version>${camel-version}</version>
</dependency>
...
</dependencies>变量
表 31.1 “SpEL 变量” 列出在使用 SpEL 时可访问的变量。
表 31.1. SpEL 变量
| 变量 | 类型 | 描述 |
|---|---|---|
|
|
| 当前交换是 root 对象。 |
|
|
| 当前交换。 |
|
|
| 当前交换的 ID。 |
|
|
| 交换例外(如果有)。 |
|
|
| 故障消息(若有)。 |
|
|
| 交换的 In 消息。 |
|
|
| 交换的 Out 消息(如果有)。 |
|
|
| 交换属性。 |
|
|
| 交换属性,由 名称 进行密钥。 |
|
|
| 由 名称 密钥的交换属性,转换为类型 类型。 |
XML 示例
例如,要仅选择其 国家 头拥有值 美国 的消息,您可以使用以下 SpEL 表达式:
<route>
<from uri="SourceURL"/>
<filter>
<spel>#{request.headers['Country'] == 'USA'}}</spel>
<to uri="TargetURL"/>
</filter>
</route>Java 示例
您可以在 Java DSL 中定义相同的路由,如下所示:
from("SourceURL")
.filter().spel("#{request.headers['Country'] == 'USA'}")
.to("TargetURL");以下示例演示了如何在纯文本字符串中嵌入 SpEL 表达式:
from("SourceURL")
.setBody(spel("Hello #{request.body}! What a beautiful #{request.headers['dayOrNight']}"))
.to("TargetURL");