# Kotlin DSL
# Kotlin dsl
Kotlin DSL 是Java DSL的包装器和扩展,其目的是使 Spring 上的集成开发尽可能平滑和简单,并与现有的 Java API 和 Kotlin 语言特定的结构具有互操作性。
所有你需要开始的只是org.springframework.integration.dsl.integrationFlow
的导入-一个 Kotlin DSL 的重载全局函数。
对于作为 lambdas 的IntegrationFlow
定义,我们通常不需要 Kotlin 中的任何其他内容,只需要像这样声明 Bean:
@Bean
fun oddFlow() =
IntegrationFlow { flow ->
flow.handle<Any> { _, _ -> "odd" }
}
在这种情况下, Kotlin 理解 Lambda 应该被转换为IntegrationFlow
匿名实例,并且目标 Java DSL 处理器将此构造正确地解析为 Java 对象。
作为上述结构的替代方案以及为了与下面解释的用例保持一致,应该使用 Kotlin-specif DSL 来声明建造者模式样式中的集成流:
@Bean
fun flowLambda() =
integrationFlow {
filter<String> { it === "test" }
wireTap {
handle { println(it.payload) }
}
transform<String, String> { it.toUpperCase() }
}
这样的全局integrationFlow()
函数需要对KotlinIntegrationFlowDefinition
(IntegrationFlowDefinition
的 Kotlin 包装器)使用构建器样式的 lambda,并生成一个常规的IntegrationFlow
lambda 实现。请参阅下面的更多重载integrationFlow()
变体。
许多其他场景需要从数据源启动IntegrationFlow
(例如JdbcPollingChannelAdapter
,JmsInboundGateway
或仅从现有的MessageChannel
)。为此目的, Spring 集成 Java DSL 提供了一个IntegrationFlows
工厂及其大量的重载from()
方法。这个工厂也可用于:
@Bean
fun flowFromSupplier() =
IntegrationFlows.from<String>({ "bar" }) { e -> e.poller { p -> p.fixedDelay(10).maxMessagesPerPoll(1) } }
.channel { c -> c.queue("fromSupplierQueue") }
.get()
但遗憾的是,并非所有from()
方法都与 Kotlin 结构兼容。为了弥补差距,该项目提供了一个围绕IntegrationFlows
工厂的 Kotlin DSL。它被实现为一组重载的integrationFlow()
函数。用一个消费者为KotlinIntegrationFlowDefinition
将流的其余部分声明为IntegrationFlow
lambda,以重用上述经验,并最终避免get()
调用。例如:
@Bean
fun functionFlow() =
integrationFlow<Function<String, String>>({ beanName("functionGateway") }) {
transform<String, String> { it.toUpperCase() }
}
@Bean
fun messageSourceFlow() =
integrationFlow(MessageProcessorMessageSource { "testSource" },
{ poller { it.fixedDelay(10).maxMessagesPerPoll(1) } }) {
channel { queue("fromSupplierQueue") }
}
此外, Kotlin 为 Java DSL API 提供了扩展,这需要对 Kotlin 结构进行一些改进。例如,IntegrationFlowDefinition<*>
需要对具有Class<P>
参数的许多方法进行具体化:
@Bean
fun convertFlow() =
integrationFlow("convertFlowInput") {
convert<TestPojo>()
}