315.3. Samples

315.3.1. 表达式模板

启用表达式时,SpEL 表达式需要被 #{ } 分隔符括起。这可让您将 SpEL 表达式与常规文本合并,并使用它作为非常轻量级的模板语言。

例如,如果您构建以下路由:

from("direct:example")
    .setBody(spel("Hello #{request.body}! What a beautiful #{request.headers['dayOrNight']}"))
    .to("mock:result");

在上面的路由中,注意 spel 是一个静态方法,我们需要从 org.apache.camel.language.spel.SpelExpression.spel 导入到 setBody 方法中传递的表达式。虽然我们使用 fluent API,但我们可以这样做:

from("direct:example")
    .setBody().spel("Hello #{request.body}! What a beautiful #{request.headers['dayOrNight']}")
    .to("mock:result");

请注意,我们现在使用 setBody () 方法的 spel 方法。这不要求我们从 org.apache.camel.language.spel.SpelExpression.spel 静态导入 spel 方法。

并发送一个在正文中带有字符串 "World" 的消息,以及带有值 "dayOrNight" 的标头 "dayOrNight":

template.sendBodyAndHeader("direct:example", "World", "dayOrNight", "day");

mock:result 上的输出为 "Hello World!什么 autiful day"