Kotlin DSL

Kotlin DSL 是 Java DSL 的包裝器和擴充功能,旨在使 Kotlin 上的 Spring Integration 開發盡可能順暢和直接,並與現有的 Java API 和 Kotlin 語言特定的結構具有互操作性。

您開始使用 Kotlin DSL 所需的僅僅是匯入 org.springframework.integration.dsl.integrationFlow - Kotlin DSL 的多載全域函數。

對於作為 lambda 的 IntegrationFlow 定義,我們通常不需要 Kotlin 的任何其他東西,只需像這樣宣告一個 bean

@Bean
fun oddFlow() =
IntegrationFlow { flow ->
    flow.handle<Any> { _, _ -> "odd" }
}

在這種情況下,Kotlin 了解 lambda 應轉換為 IntegrationFlow 匿名實例,並且目標 Java DSL 處理器會將此建構正確地解析為 Java 物件。

作為上述建構的替代方案,並為了與下面解釋的用例保持一致,Kotlin 特定的 DSL 應用於以 builder 模式樣式宣告整合流

@Bean
fun flowLambda() =
    integrationFlow {
        filter<String> { it === "test" }
        wireTap {
                    handle { println(it.payload) }
                }
        transform<String> { it.toUpperCase() }
    }

這樣一個全域 integrationFlow() 函數需要一個 builder 樣式的 lambda 作為 `KotlinIntegrationFlowDefinition`(`IntegrationFlowDefinition` 的 Kotlin 包裝器),並產生常規的 `IntegrationFlow` lambda 實作。請參閱下面更多重載的 `integrationFlow()` 變體。

許多其他情境需要從資料來源啟動 `IntegrationFlow` (例如 `JdbcPollingChannelAdapter`、`JmsInboundGateway` 或僅僅是現有的 `MessageChannel`)。為此,Spring Integration Java DSL 提供了 `IntegrationFlow` fluent API 及其大量重載的 `from()` 方法。這個 API 也可以在 Kotlin 中使用

@Bean
fun flowFromSupplier() =
         IntegrationFlow.fromSupplier({ "bar" }) { e -> e.poller { p -> p.fixedDelay(10).maxMessagesPerPoll(1) } }
                 .channel { c -> c.queue("fromSupplierQueue") }
                 .get()

但遺憾的是,並非所有 `from()` 方法都與 Kotlin 結構相容。為了彌補差距,此專案在 `IntegrationFlow` fluent API 周圍提供了 Kotlin DSL。它實作為一組重載的 `integrationFlow()` 函數。使用 `KotlinIntegrationFlowDefinition` 的消費者將流程的其餘部分宣告為 `IntegrationFlow` lambda,以重用上述經驗,並避免在最後呼叫 `get()`。例如

@Bean
fun functionFlow() =
        integrationFlow<Function<String, String>>({ beanName("functionGateway") }) {
            transform<String> { it.toUpperCase() }
        }

@Bean
fun messageSourceFlow() =
        integrationFlow(MessageProcessorMessageSource { "testSource" },
                { poller { it.fixedDelay(10).maxMessagesPerPoll(1) } }) {
            channel { queue("fromSupplierQueue") }
        }

此外,為 Java DSL API 提供了 Kotlin 擴充功能,Java DSL API 需要針對 Kotlin 結構進行一些改進。例如,`IntegrationFlowDefinition<*>` 需要對許多帶有 `Class<P>` 參數的方法進行具體化

@Bean
fun convertFlow() =
    integrationFlow("convertFlowInput") {
        convert<TestPojo>()
    }
如果需要在運算子的 lambda 中也存取標頭,則具體化的類型可以是整個 `Message<*>`。