Java DSL

Spring Integration Java 設定和 DSL 提供了一組方便的建構器和流暢的 API,可讓您從 Spring `@Configuration` 類別設定 Spring Integration 訊息流程。

(另請參閱 Kotlin DSL。)

(另請參閱 Groovy DSL。)

Spring Integration 的 Java DSL 本質上是 Spring Integration 的一個外觀模式。DSL 提供了一種簡單的方式,透過使用流暢的 `Builder` 模式以及來自 Spring Framework 和 Spring Integration 的現有 Java 設定,將 Spring Integration 訊息流程嵌入到您的應用程式中。我們也使用並支援 lambda (Java 8 中可用),以進一步簡化 Java 設定。

cafe 提供了一個使用 DSL 的良好範例。

DSL 由 `IntegrationFlow` 流暢 API (請參閱 `IntegrationFlowBuilder`) 呈現。這會產生 `IntegrationFlow` 元件,該元件應註冊為 Spring bean (透過使用 `@Bean` 註解)。建構器模式用於將任意複雜的結構表示為方法層次結構,這些方法可以接受 lambda 作為引數。

`IntegrationFlowBuilder` 僅在 `IntegrationFlow` bean 中收集整合元件 (`MessageChannel` 實例、`AbstractEndpoint` 實例等等),以便 `IntegrationFlowBeanPostProcessor` 在應用程式內容中進一步解析和註冊具體 bean。

Java DSL 直接使用 Spring Integration 類別,並繞過任何 XML 產生和解析。然而,DSL 提供的不僅僅是 XML 之上的語法糖。其最引人注目的功能之一是能夠定義內聯 lambda 來實作端點邏輯,從而無需外部類別來實作自訂邏輯。在某種程度上,Spring Integration 對 Spring Expression Language (SpEL) 和內聯腳本的支援解決了這個問題,但 lambda 更容易且功能更強大。

以下範例示範如何為 Spring Integration 使用 Java 設定

@Configuration
@EnableIntegration
public class MyConfiguration {

    @Bean
    public AtomicInteger integerSource() {
        return new AtomicInteger();
    }

    @Bean
    public IntegrationFlow myFlow(AtomicInteger integerSource) {
        return IntegrationFlow.fromSupplier(integerSource::getAndIncrement,
                                         c -> c.poller(Pollers.fixedRate(100)))
                    .channel("inputChannel")
                    .filter((Integer p) -> p > 0)
                    .transform(Object::toString)
                    .channel(MessageChannels.queue())
                    .get();
    }
}

上述設定範例的結果是,它會在 `ApplicationContext` 啟動後建立 Spring Integration 端點和訊息通道。Java 設定可用於取代和擴充 XML 設定。您無需替換所有現有的 XML 設定即可使用 Java 設定。