kotlin-dsl.md 3.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
# Kotlin DSL

##  Kotlin dsl

Kotlin DSL 是[Java DSL](./dsl.html#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>()
    }
```