更上一层楼
VMware 提供培训和认证,以加速您的进步。
了解更多Spring Integration 使用 Spring 编程模型实现 企业集成模式,从而在基于 Spring 的应用程序中启用消息传递。Spring Integration 还提供与外部系统的集成,使用声明性适配器支持 jms、http、amqp、tcp、ftp(s)、smtp 等。目前,消息流的配置主要通过 Spring XML 完成,Spring Integration 支持多个命名空间以尽可能简洁。今年早些时候,SpringSource 发布了用于 Spring Integration 的 Scala DSL。现在,我们很高兴宣布 Groovy DSL 的第一个里程碑版本 (1.0.0.M1)。
这两个 DSL 都有一个共同的目标 - 为 Spring Integration 提供一个强大而灵活的 XML 配置替代方案。这两种语言在语义上也相似,因为 Groovy DSL 从 Scala DSL 引入的概念中汲取灵感。此外,两者本质上都是 Spring Integration 之上的一个外观。然而,相似之处到此为止。许多差异可以归因于 Scala 和 Groovy 之间的语言差异,最值得注意的是,静态类型与动态类型。Groovy DSL 主要针对 Groovyists,他们对 DSL 基于的 构建器模式 的分层语法感到满意。这也应该吸引 Java 开发人员,他们可以利用 DSL 提供的丰富功能,并且会发现该语法非常平易近人。
def builder = new IntegrationBuilder()
def flow = builder.messageFlow {
transform {"hello, $it"}
handle {println it}
}
flow.send('world')
这会创建一个 Spring 应用程序上下文,构建一个由转换器 (transform) 和服务激活器 (handle) 组成的 Spring Integration 消息流,并使用直接通道连接这些端点,以便它们按顺序执行。转换器将消息有效负载(在本例中为“world”)附加到字符串“hello, ”,服务激活器将结果打印到 STDOUT。瞧!这里我们看到了构建器模式的一个简单实例。对于那些不熟悉 Groovy 的人来说,这是有效的 Groovy 语法。messageFlow、transform 和 handle 都是由 DSL 定义的方法。{} 是 Groovy 中闭包的语法。由于括号和分号在 Groovy 中是可选的,因此这相当于
def flow = builder.messageFlow({
transform({"hello, $it"});
handle({println(it)});
});
此外,我应该提到,默认情况下,Groovy 闭包期望一个名为“it”的参数。闭包参数可以命名并且可以选择类型。例如
transform {String payload -> "hello, $payload"}
还有一件事。Groovy 允许您在双引号字符串中嵌入变量表达式。这并非旨在成为 Groovy 教程,但足以说明 Groovy 的所有语法糖使代码非常简洁、易读。顺便说一句,这等效的 XML 是
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:si="http://www.springframework.org/schema/integration" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd">
<si:transformer id="t1" input-channel="flow1.inputChannel" output-channel="sa1.inputChannel" expression="'Hello,' + payload"/>
<si:service-activator id="sa1" input-channel="sa.inputChannel" expression = "T(java.lang.System).out.println(payload)"/>
</beans>
然后我们必须编写大约十行代码来初始化 Spring 应用程序上下文并发送消息。
要在 Java 中运行 DSL 示例,有几种选择。一种方法是加载并运行外部 DSL 脚本
HelloWorld.groovy
messageFlow {
transform {"hello, $it"}
handle {println it}
}
Main.java
public class Main {
public static void main(String[] args) {
IntegrationBuilder builder = new IntegrationBuilder();
MessageFlow flow = (MessageFlow) builder.build(new File("HelloWorld.groovy"));
flow.send("world");
}
}
除了如上所示的 File 实例外,build() 方法还接受 InputStream、GroovyCodeSource、Spring Resource,甚至是 groovy.lang.Script。因此,如果您使用 Groovy 编译器编译您的项目,您可以这样做,其中 HelloWorld 是 groovy.lang.Script 的一个实例。
public class Main {
public static void main(String[] args) {
IntegrationBuilder builder = new IntegrationBuilder();
MessageFlow flow = (MessageFlow) builder.build(new HelloWorld()));
flow.send("world");
}
}