316.3. Samples
316.3.1. 表达式模板 复制链接链接已复制到粘贴板!
因为启用了表达式模板,SpEL 表达式需要用 #{
}
分隔符周围。这可让您将 SpEL 表达式与正则表达式相结合,并将其用作非常轻量级模板语言。
例如,如果您构建以下路由:
from("direct:example") .setBody(spel("Hello #{request.body}! What a beautiful #{request.headers['dayOrNight']}")) .to("mock:result");
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
导入,因为我们将 spel 用作参数传递给 setBody
方法。虽然我们使用流畅的 API,我们可以这样做:
from("direct:example") .setBody().spel("Hello #{request.body}! What a beautiful #{request.headers['dayOrNight']}") .to("mock:result");
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",值为 "day":
template.sendBodyAndHeader("direct:example", "World", "dayOrNight", "day");
template.sendBodyAndHeader("direct:example", "World", "dayOrNight", "day");
模拟的输出将是 "Hello World!很小的天子"。
316.3.2. Bean 集成 复制链接链接已复制到粘贴板!
您可以在 SpEL 表达式中引用 Registry 中定义的 Bean (很可能是 ApplicationContext
)。例如,如果您的 ApplicationContext
中有一个名为 "foo" 的 bean,您可以在这个 bean 上调用 "bar" 方法,如下所示:
#{@foo.bar == 'xyz'}
#{@foo.bar == 'xyz'}
316.3.3. 企业集成模式的 SpEL 复制链接链接已复制到粘贴板!
您可以将 SpEL 用作 Recipient List 的表达式,或者在 Message Filter 中作为 predicate:
以及 Java DSL 中的等效内容:
from("direct:foo") .filter().spel("#{request.headers['foo'] == 'bar'}") .to("direct:bar");
from("direct:foo")
.filter().spel("#{request.headers['foo'] == 'bar'}")
.to("direct:bar");