Spring Integration: channels, flows and gateways

Spring Integration implements the Enterprise Integration Patterns inside a Spring application: messages travel through channels between small endpoints that filter, route, transform and combine them. This page explains the model, then runs complete Spring Boot 4.1 programs for channels, the Java DSL, gateways, splitting and aggregating, error handling and polling.

Contents

Messages, channels and endpoints

Spring Integration is Spring's implementation of the Enterprise Integration Patterns, the catalogue of messaging patterns described by Gregor Hohpe and Bobby Woolf. Instead of one service method calling the next, the steps of a process exchange messages, and each step only knows the channel it reads from and the channel it writes to. That makes it easy to add a step, run a step on another thread, or replace an in-memory channel with a file, a queue or an HTTP call.

Three building blocks make up every integration:

  • Message: an immutable payload plus headers, the org.springframework.messaging.Message type shared with Spring's other messaging modules. Headers carry ids, correlation data, reply addresses and your own values.
  • Channel: the pipe between steps. Its type decides whether the next step runs on the sender's thread, on another thread, or later, when someone polls.
  • Endpoint: a step that consumes from a channel. The common ones are filter, transformer, router, splitter, aggregator and service activator (a plain handler method), plus gateways and channel adapters at the edges.
Endpoints and the patterns they implement
DSL methodPatternWhat it does
filterMessage filterPasses or drops a message, optionally to a discard flow
transformMessage translatorChanges the payload
enrichHeadersContent enricherAdds headers
routeContent-based routerSends each message to one of several channels or sub-flows
split, aggregateSplitter, aggregatorBreaks a message into parts and joins the results back
handleService activatorCalls your code, optionally producing a reply
wireTapWire tapCopies messages to a side flow, for auditing or debugging
IntegrationFlow.from(Interface.class)Messaging gatewayLets plain Java code send messages and wait for replies

The examples are Spring Boot 4.1 applications using spring-boot-starter-integration, which brings Spring Integration 7.1 and auto-configures the infrastructure: the global errorChannel, a taskScheduler for pollers and gateway scanning. Everything runs in memory. Adapters for files, HTTP, JMS, Kafka, JDBC and others live in separate modules; the last section adds spring-integration-file 7.1.2 and runs a file flow.

Channel types and the threads they use

The channel type is the most important design decision in a flow, because it decides threading, buffering and how errors travel. Channels are plain objects, so this program creates each type directly and sends to it; the Spring Boot context only sets up logging:

Java
package demo.integration.channels;

import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.channel.ExecutorChannel;
import org.springframework.integration.channel.PublishSubscribeChannel;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageDeliveryException;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.support.MessageBuilder;

@SpringBootApplication
public class ChannelTypes {

    static String thread() {
        return Thread.currentThread().getName().replaceAll("-\\d+$", "-N");
    }

    static MessageHandler printer(String name) {
        return message -> System.out.println("   " + name + " got '" + message.getPayload()
                + "' on " + thread());
    }

    public static void main(String[] args) throws Exception {
        // the context is only used for its logging setup; the channels are plain objects
        SpringApplication app = new SpringApplication(ChannelTypes.class);
        app.setDefaultProperties(Map.of("spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        app.run(args).close();

        System.out.println("1. DirectChannel: one subscriber per message, on the sender's thread");
        DirectChannel direct = new DirectChannel();
        direct.subscribe(printer("A"));
        direct.subscribe(printer("B"));
        for (int i = 1; i <= 3; i++) {
            direct.send(MessageBuilder.withPayload("order " + i).build());
        }

        System.out.println("2. DirectChannel: a failing subscriber fails the send() call");
        DirectChannel failing = new DirectChannel();
        failing.subscribe(message -> {
            throw new IllegalStateException("database down");
        });
        try {
            failing.send(MessageBuilder.withPayload("order 4").build());
        } catch (RuntimeException e) {
            System.out.println("   send() threw " + e.getClass().getSimpleName()
                    + ", cause: " + e.getCause().getMessage());
        }

        System.out.println("3. DirectChannel with no subscriber:");
        try {
            new DirectChannel().send(MessageBuilder.withPayload("lost").build());
        } catch (MessageDeliveryException e) {
            System.out.println("   " + e.getClass().getSimpleName());
        }

        System.out.println("4. PublishSubscribeChannel: every subscriber gets every message");
        PublishSubscribeChannel pubSub = new PublishSubscribeChannel();
        pubSub.subscribe(printer("email"));
        pubSub.subscribe(printer("audit"));
        pubSub.send(MessageBuilder.withPayload("order 5").build());

        System.out.println("5. QueueChannel: messages wait until a consumer polls");
        QueueChannel queue = new QueueChannel(2);
        System.out.println("   send 1: " + queue.send(MessageBuilder.withPayload("a").build(), 0));
        System.out.println("   send 2: " + queue.send(MessageBuilder.withPayload("b").build(), 0));
        System.out.println("   send 3 to a full queue: "
                + queue.send(MessageBuilder.withPayload("c").build(), 0));
        Message<?> first = queue.receive(100);
        System.out.println("   received '" + first.getPayload() + "', queue size now "
                + queue.getQueueSize());

        System.out.println("6. ExecutorChannel: the subscriber runs on a pool thread");
        CountDownLatch done = new CountDownLatch(1);
        AtomicReference<String> handledOn = new AtomicReference<>();
        try (var pool = Executors.newSingleThreadExecutor(r -> new Thread(r, "worker-1"))) {
            ExecutorChannel async = new ExecutorChannel(pool);
            async.subscribe(message -> {
                handledOn.set(thread());
                done.countDown();
            });
            boolean sent = async.send(MessageBuilder.withPayload("order 6").build());
            System.out.println("   send() returned " + sent + " on " + thread());
            done.await(5, TimeUnit.SECONDS);
            System.out.println("   the handler ran on " + handledOn.get());
        }
    }
}
Output
1. DirectChannel: one subscriber per message, on the sender's thread
   A got 'order 1' on main
   B got 'order 2' on main
   A got 'order 3' on main
2. DirectChannel: a failing subscriber fails the send() call
   send() threw MessageDeliveryException, cause: database down
3. DirectChannel with no subscriber:
   MessageDeliveryException
4. PublishSubscribeChannel: every subscriber gets every message
   email got 'order 5' on main
   audit got 'order 5' on main
5. QueueChannel: messages wait until a consumer polls
   send 1: true
   send 2: true
   send 3 to a full queue: false
   received 'a', queue size now 1
6. ExecutorChannel: the subscriber runs on a pool thread
   send() returned true on main
   the handler ran on worker-N
  • The DirectChannel with two subscribers delivered each message to one of them, in turn: A, B, A. Both ran on main, the sender's thread, so send() returned only after the handler had finished.
  • When the only subscriber threw, send() threw a MessageDeliveryException whose cause is the handler's exception. With a direct channel, the sender sees failures at once, and a surrounding transaction covers the handler too.
  • A DirectChannel with no subscriber cannot deliver at all, so the send failed. In a real flow this usually means a missing or misspelled channel name.
  • The PublishSubscribeChannel gave the same message to both email and audit.
  • The QueueChannel with capacity 2 accepted two messages and refused the third: send(message, 0) returned false instead of waiting. A consumer took a with receive, leaving one message.
  • The ExecutorChannel returned true straight away and the handler ran on worker-1, so the sender can no longer see the handler's result or its exceptions. The program records the handler's thread and prints it after waiting, because the two threads would otherwise print in no fixed order.

A DirectChannel with several subscribers also fails over by default: if one subscriber throws, the next one is tried, and the sender sees an error only when all have failed. setFailover(false) turns that off.

A flow with the Java DSL and a gateway

Real flows are declared as IntegrationFlow beans with the Java DSL, which creates the channels between steps for you. This order flow starts at a gateway interface, audits every order with a wire tap, rejects empty orders, adds a VAT header and routes by country to one of two warehouses:

Java
package demo.integration.flow;

import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.handler.annotation.Header;

@SpringBootApplication
public class OrderFlow {

    record Order(String id, String country, int totalCents) { }

    // The application only sees this interface; Spring Integration implements it
    interface OrderGateway {
        String place(Order order, @Header("source") String source);
    }

    @Bean
    IntegrationFlow orders() {
        return IntegrationFlow.from(OrderGateway.class)
                // a wire tap copies each message to a side flow, here for auditing
                .wireTap(tap -> tap.handle(m -> System.out.println("  [audit] "
                        + m.getPayload() + " from " + m.getHeaders().get("source"))))
                .<Order>filter(o -> o.totalCents() > 0, f -> f.discardFlow(
                        d -> d.handle((p, h) -> "rejected " + ((Order) p).id() + ": empty")))
                .enrichHeaders(h -> h.headerFunction("vatPercent",
                        m -> ((Order) m.getPayload()).country().equals("DE") ? 19 : 20))
                .<Order, String>route(Order::country, r -> r
                        .subFlowMapping("DE", sf -> sf.handle(OrderFlow::shipFromBerlin))
                        .defaultSubFlowMapping(sf -> sf.handle(OrderFlow::shipFromLyon)))
                .get();
    }

    static String shipFromBerlin(Order order, MessageHeaders headers) {
        return "Berlin ships " + order.id() + ", VAT " + headers.get("vatPercent") + "%";
    }

    static String shipFromLyon(Order order, MessageHeaders headers) {
        return "Lyon ships " + order.id() + ", VAT " + headers.get("vatPercent") + "%";
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(OrderFlow.class);
        app.setDefaultProperties(Map.of("spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        try (var context = app.run(args)) {
            OrderGateway gateway = context.getBean(OrderGateway.class);
            System.out.println("gateway is a proxy: "
                    + gateway.getClass().getSimpleName().startsWith("$Proxy"));
            System.out.println(gateway.place(new Order("o-1", "DE", 4999), "web"));
            System.out.println(gateway.place(new Order("o-2", "FR", 1200), "mobile"));
            System.out.println(gateway.place(new Order("o-3", "FR", 0), "web"));
        }
    }
}
Output
gateway is a proxy: true
  [audit] Order[id=o-1, country=DE, totalCents=4999] from web
Berlin ships o-1, VAT 19%
  [audit] Order[id=o-2, country=FR, totalCents=1200] from mobile
Lyon ships o-2, VAT 20%
  [audit] Order[id=o-3, country=FR, totalCents=0] from web
rejected o-3: empty
  • OrderGateway is a plain interface. IntegrationFlow.from(OrderGateway.class) made Spring create a JDK proxy for it and register it as a bean, so calling code never touches the messaging API.
  • The @Header("source") parameter became a message header, which the wire tap printed: web, then mobile.
  • The wire tap's audit line came before each result, because the tap's side flow ran on the same thread before the main flow continued.
  • o-1 is German, so the router sent it to the DE sub-flow, which read the vatPercent header of 19. o-2 went to the default sub-flow with 20%.
  • o-3 has a total of 0, so the filter discarded it. The discard flow produced a reply, and the gateway returned it as rejected o-3: empty.

The gateway method returns a String, so the gateway waited for a reply. It sent the request with a temporary reply channel in its headers, and the last endpoint of whichever branch ran sent its result there. A gateway method returning void sends and returns at once, without waiting.

Annotating the interface with @MessagingGateway is the other way to declare a gateway; Spring Boot scans for those. Use one way or the other: declaring the same interface with both creates two beans, and asking for the interface by type then fails.

Splitting work and aggregating the results

A splitter breaks one message into several, and an aggregator collects the results back into one, which is the usual way to process the parts of a request in parallel. Each cart line here is priced on a pool thread. The simulated pricing calls take 300 ms for pens, 100 ms for books and 200 ms for mugs, so the lines finish in a different order from the cart:

Java
package demo.integration.split;

import java.util.List;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.IntegrationMessageHeaderAccessor;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.MessageChannels;
import org.springframework.messaging.Message;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@SpringBootApplication
public class SplitAggregate {

    record Line(String sku, int quantity) { }

    record Cart(String id, List<Line> lines) { }

    record Priced(String sku, int sequence, int cents) { }

    interface Checkout {
        String total(Cart cart);
    }

    // price per item, and how long the (simulated) pricing service takes for it
    static final Map<String, Integer> PRICES = Map.of("pen", 150, "book", 1299, "mug", 800);
    static final Map<String, Integer> DELAYS = Map.of("pen", 300, "book", 100, "mug", 200);

    @Bean
    ThreadPoolTaskExecutor pricingPool() {
        ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
        pool.setCorePoolSize(3);
        pool.setThreadNamePrefix("pricing-");
        return pool;
    }

    @Bean
    IntegrationFlow checkout(ThreadPoolTaskExecutor pricingPool) {
        return IntegrationFlow.from(Checkout.class)
                .split(Cart.class, Cart::lines)
                // each line is priced on its own thread, in parallel
                .channel(MessageChannels.executor(pricingPool))
                .handle(Line.class, (line, headers) -> {
                    sleep(DELAYS.get(line.sku()));
                    int sequence = (Integer) headers.get(
                            IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER);
                    return new Priced(line.sku(), sequence,
                            PRICES.get(line.sku()) * line.quantity());
                })
                .aggregate(a -> a.outputProcessor(group -> {
                    int total = 0;
                    StringBuilder arrival = new StringBuilder();
                    for (Message<?> m : group.getMessages()) {
                        Priced p = (Priced) m.getPayload();
                        total += p.cents();
                        arrival.append(p.sku()).append("(line ").append(p.sequence())
                                .append(") ");
                    }
                    return "arrived " + arrival + "-> " + group.size() + " lines, total "
                            + total / 100.0 + " EUR";
                }))
                .get();
    }

    static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(SplitAggregate.class);
        app.setDefaultProperties(Map.of("spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        try (var context = app.run(args)) {
            Checkout checkout = context.getBean(Checkout.class);
            Cart cart = new Cart("c-1", List.of(new Line("pen", 4), new Line("book", 1),
                    new Line("mug", 2)));
            long start = System.nanoTime();
            System.out.println("cart c-1: " + checkout.total(cart));
            System.out.println("took about " + Math.round((System.nanoTime() - start)
                    / 1000000 / 100.0) * 100 + " ms for 300 + 100 + 200 ms of pricing");
        }
    }
}
Output
cart c-1: arrived book(line 2) mug(line 3) pen(line 1) -> 3 lines, total 34.99 EUR
took about 300 ms for 300 + 100 + 200 ms of pricing
  • The splitter turned the cart into three messages and gave each one sequenceNumber, sequenceSize and correlationId headers.
  • The executor channel priced the three lines in parallel on the pricing- pool. They arrived at the aggregator in finishing order: book (line 2), mug (line 3), then pen (line 1).
  • The aggregator grouped them by correlation id and released the group when all three of the sequenceSize parts were in. The total, 4 x 1.50 + 12.99 + 2 x 8.00, is 34.99 EUR.
  • The whole checkout took about as long as the slowest line, not the 600 ms sum.

The aggregator keeps incomplete groups in a message store, in memory by default. If one part never arrives, the group waits forever unless you set groupTimeout and decide what to do with partial groups. For aggregation that must survive a restart, use a persistent store such as JdbcMessageStore. The pool is a Spring bean so that the context shuts it down; an Executors pool created inline would keep the JVM running after the context closed.

Errors: thrown, replied or sent to errorChannel

Where an exception goes depends on the thread it happens on. This program has a payment flow that declines one card number, a variant whose gateway has an error channel, and a notification flow that fails on another thread:

Java
package demo.integration.errors;

import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.MessageChannels;
import org.springframework.messaging.MessagingException;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@SpringBootApplication
public class ErrorChannels {

    static final CountDownLatch ASYNC_ERROR = new CountDownLatch(1);

    interface Payments {
        String charge(String card);
    }

    interface SafePayments {
        String charge(String card);
    }

    @MessagingGateway(defaultRequestChannel = "notifications.input")
    interface Notifier {
        void notify(String text);
    }

    static String charge(String card) {
        if (card.startsWith("0000")) {
            throw new IllegalArgumentException("card " + card + " declined");
        }
        return "charged " + card;
    }

    @Bean
    IntegrationFlow payments() {
        return IntegrationFlow.from(Payments.class)
                .<String, String>transform(ErrorChannels::charge)
                .get();
    }

    @Bean
    IntegrationFlow safePayments() {
        return IntegrationFlow.from(SafePayments.class, g -> g.errorChannel("paymentErrors"))
                .<String, String>transform(ErrorChannels::charge)
                .get();
    }

    // the gateway's error channel: its reply goes back to the caller instead of the error
    @Bean
    IntegrationFlow paymentErrorFlow() {
        return IntegrationFlow.from("paymentErrors")
                .<MessagingException, String>transform(e -> "fallback: "
                        + e.getCause().getMessage() + ", queued for manual review")
                .get();
    }

    @Bean
    ThreadPoolTaskExecutor mailPool() {
        ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
        pool.setThreadNamePrefix("mail-");
        return pool;
    }

    // fire and forget, handled on another thread: nobody waits for the outcome
    @Bean
    IntegrationFlow notifications(ThreadPoolTaskExecutor mailPool) {
        return f -> f.channel(MessageChannels.executor(mailPool))
                .handle(m -> {
                    throw new IllegalStateException("SMTP server unreachable");
                });
    }

    // the global errorChannel receives failures from asynchronous flows
    @Bean
    IntegrationFlow globalErrors() {
        return IntegrationFlow.from("errorChannel")
                .handle(m -> {
                    MessagingException e = (MessagingException) m.getPayload();
                    System.out.println("  [errorChannel] " + e.getClass().getSimpleName()
                            + ": " + e.getCause().getMessage() + ", failed payload '"
                            + e.getFailedMessage().getPayload() + "'");
                    ASYNC_ERROR.countDown();
                })
                .get();
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(ErrorChannels.class);
        app.setDefaultProperties(Map.of("spring.main.banner-mode", "off",
                "logging.level.root", "OFF"));
        try (var context = app.run(args)) {
            Payments payments = context.getBean(Payments.class);
            System.out.println("1. Synchronous flow: the exception reaches the caller");
            System.out.println("   " + payments.charge("4111-1111"));
            try {
                payments.charge("0000-0000");
            } catch (RuntimeException e) {
                System.out.println("   caught " + e.getClass().getSimpleName() + ": "
                        + e.getMessage());
            }

            System.out.println("2. Gateway with an errorChannel: the caller gets a reply");
            System.out.println("   " + context.getBean(SafePayments.class).charge("0000-0000"));

            System.out.println("3. Asynchronous flow: the caller cannot see the error");
            context.getBean(Notifier.class).notify("your order shipped");
            System.out.println("   notify() returned normally");
            ASYNC_ERROR.await(5, TimeUnit.SECONDS);
        }
    }
}
Output
1. Synchronous flow: the exception reaches the caller
   charged 4111-1111
   caught IllegalArgumentException: card 0000-0000 declined
2. Gateway with an errorChannel: the caller gets a reply
   fallback: card 0000-0000 declined, queued for manual review
3. Asynchronous flow: the caller cannot see the error
   notify() returned normally
  [errorChannel] MessageDeliveryException: SMTP server unreachable, failed payload 'your order shipped'
  • The payment flow ran on the caller's thread, so the exception came back through the gateway. The gateway unwrapped Spring Integration's MessageHandlingException and rethrew the original IllegalArgumentException, so the caller can catch its own exception type.
  • The second gateway was given errorChannel("paymentErrors"). The failure was sent there as an ErrorMessage, and the reply of the error flow became the gateway's return value: a fallback instead of an exception.
  • The notification gateway returns void and the flow handed the message to the mail- pool, so notify() returned normally. The exception then went to the global errorChannel, wrapped in a MessageDeliveryException that still holds the failed message.

By default, the global errorChannel has one subscriber that logs at ERROR level, which is easy to miss in production. Subscribe your own flow to it, as globalErrors does, to count failures, store failed messages or alert someone. Pollers and message-driven adapters also send their errors there.

Polling a source

Many sources cannot push messages: a database table, a directory, a mailbox. A polling channel adapter checks them on a schedule and turns each new item into a message. Here a queue of five invoices stands in for such a source, polled every 200 ms with at most two items per poll:

Java
package demo.integration.polling;

import java.time.Duration;
import java.util.ArrayDeque;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.Pollers;

@SpringBootApplication
public class PollingSource {

    // stands in for a table, a directory or a mailbox that is checked periodically
    static final Queue<String> INBOX = new ArrayDeque<>(List.of("invoice-1", "invoice-2",
            "invoice-3", "invoice-4", "invoice-5"));
    static final CountDownLatch DONE = new CountDownLatch(5);
    static volatile long first;

    static synchronized String nextOrNull() {
        return INBOX.poll(); // null means "nothing new": no message is created
    }

    @Bean
    IntegrationFlow invoices() {
        return IntegrationFlow.fromSupplier(PollingSource::nextOrNull,
                        e -> e.poller(Pollers.fixedDelay(Duration.ofMillis(200))
                                .maxMessagesPerPoll(2)))
                .<String, String>transform(String::toUpperCase)
                .handle(m -> {
                    long now = System.nanoTime();
                    if (first == 0) {
                        first = now;
                    }
                    long ms = Math.round((now - first) / 1000000 / 100.0) * 100;
                    System.out.println("  at about " + ms + " ms: " + m.getPayload()
                            + " on " + Thread.currentThread().getName()
                                    .replaceAll("-\\d+$", "-N"));
                    DONE.countDown();
                })
                .get();
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(PollingSource.class);
        app.setDefaultProperties(Map.of("spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        var context = app.run(args);
        System.out.println("all 5 handled: " + DONE.await(10, TimeUnit.SECONDS));
        context.close();
    }
}
Output
at about 0 ms: INVOICE-1 on scheduling-N
  at about 0 ms: INVOICE-2 on scheduling-N
  at about 200 ms: INVOICE-3 on scheduling-N
  at about 200 ms: INVOICE-4 on scheduling-N
  at about 400 ms: INVOICE-5 on scheduling-N
all 5 handled: true
  • The first poll took two invoices, the next poll, about 200 ms later, two more, and the third poll the last one. maxMessagesPerPoll(2) limited each poll.
  • When the supplier returned null, no message was created, so later polls did nothing.
  • The polls ran on scheduling-N, a thread of the TaskScheduler that Spring Boot auto-configures, and the rest of the flow ran on that thread too.

fixedDelay waits the given time after a poll finishes, so slow processing pushes the next poll back; fixedRate keeps a steady schedule, and cron takes a cron expression. Spring Boot can also set a default poller through spring.integration.poller.* properties.

Channel adapters for external systems

Adapters connect a flow to the outside world. Each lives in its own module, and in the Java DSL each module has a factory class: Files, Http, Jms, Kafka, Jdbc, Mail and others. The flow below moves CSV files from an inbox directory to a processed directory, turning their content to upper case on the way. It needs spring-integration-file, whose DSL factory is also called Files, the same simple name as java.nio.file.Files; the program uses the full name for the Spring one. The directories are created under the system temp directory and deleted at the end:

Java
package demo.integration.files;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.Comparator;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.Pollers;
import org.springframework.integration.file.FileHeaders;
import org.springframework.integration.file.dsl.FileWritingMessageHandlerSpec;
import org.springframework.integration.file.support.FileExistsMode;

@SpringBootApplication
public class FileFlow {

    static Path inbox;
    static Path processed;
    static final LinkedBlockingQueue<String> WRITTEN = new LinkedBlockingQueue<>();

    @Bean
    IntegrationFlow csvImport() {
        FileWritingMessageHandlerSpec writer =
                org.springframework.integration.file.dsl.Files     // clashes with nio Files
                        .outboundGateway(processed.toFile())
                        .fileExistsMode(FileExistsMode.REPLACE);
        return IntegrationFlow
                .from(org.springframework.integration.file.dsl.Files     // same clash
                                .inboundAdapter(inbox.toFile(),
                                        Comparator.comparing(File::getName))
                                .patternFilter("*.csv"),
                        e -> e.poller(Pollers.fixedDelay(Duration.ofMillis(100))))
                .enrichHeaders(h -> h.headerExpression("source",
                        "headers['" + FileHeaders.FILENAME + "']"))
                .transform(org.springframework.integration.file.dsl.Files.toStringTransformer())
                .<String, String>transform(String::toUpperCase)
                .handle(writer)
                .handle(m -> WRITTEN.add(m.getHeaders().get("source") + " -> processed/"
                        + ((File) m.getPayload()).getName()))
                .get();
    }

    static void show(String label) throws InterruptedException {
        System.out.println(label);
        String line;
        while ((line = WRITTEN.poll(600, TimeUnit.MILLISECONDS)) != null) {
            System.out.println("  " + line);
        }
    }

    public static void main(String[] args) throws Exception {
        Path root = Files.createTempDirectory("si-files");
        inbox = Files.createDirectory(root.resolve("inbox"));
        processed = Files.createDirectory(root.resolve("processed"));
        Files.writeString(inbox.resolve("orders.csv"), "id,sku\n1,book\n");
        Files.writeString(inbox.resolve("customers.csv"), "id,name\n7,ann\n");
        Files.writeString(inbox.resolve("readme.txt"), "not a csv\n");

        SpringApplication app = new SpringApplication(FileFlow.class);
        app.setDefaultProperties(Map.of("spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        var context = app.run(args);
        show("First polls:");
        System.out.println("  processed/orders.csv contains: "
                + Files.readString(processed.resolve("orders.csv")).strip()
                        .replace("\n", " | "));

        Files.writeString(inbox.resolve("orders.csv"), "id,sku\n1,book\n2,pen\n");
        Files.writeString(inbox.resolve("returns.csv"), "id,sku\n9,lamp\n");
        show("After changing orders.csv and adding returns.csv:");
        System.out.println("  still in inbox: " + list(inbox));
        context.close();
        for (Path dir : new Path[] {inbox, processed}) {
            try (var files = Files.list(dir)) {
                files.forEach(FileFlow::delete);
            }
            delete(dir);
        }
        delete(root);
    }

    static String list(Path dir) throws IOException {
        try (var files = Files.list(dir)) {
            return files.map(p -> p.getFileName().toString()).sorted().toList().toString();
        }
    }

    static void delete(Path path) {
        try {
            Files.delete(path);
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }
}
Output
First polls:
  customers.csv -> processed/customers.csv
  orders.csv -> processed/orders.csv
  processed/orders.csv contains: ID,SKU | 1,BOOK
After changing orders.csv and adding returns.csv:
  returns.csv -> processed/returns.csv
  still in inbox: [customers.csv, orders.csv, readme.txt, returns.csv]
  • The inbound adapter picked up customers.csv and orders.csv, in name order because of the comparator, and skipped readme.txt because of patternFilter("*.csv"). Each File became one message.
  • toStringTransformer() read each file's content into a String, and the outbound gateway wrote the upper-cased result to processed under the original name, taken from the file_name header. Being a gateway rather than an adapter, it replied with the written File, so the flow could continue and report it.
  • After orders.csv was rewritten with a second line, it was not processed again; only the new returns.csv was. The default filter accepts each file once, and remembers that in memory only, so a restart would process every file in the directory again.
  • The source files stayed in inbox. The adapter neither moves nor deletes them by itself.

For production, delete or move the source file after it has been handled, for example with .handle(...) that deletes the path from the file_originalFile header, or use a FileSystemPersistentAcceptOnceFileListFilter backed by a MetadataStore so that the record of processed files survives restarts. Writers on the other side should create files under a temporary name and rename them when complete, or the adapter can pick up a half-written file. The rest of the flow is the same DSL as in the examples above: adapters replace only the ends.

Choosing channels and patterns

Common needs and what to use
NeedUse
Steps that must run in the caller's thread and transactionDirectChannel, the DSL's default between steps
Hand work to a pool and return at onceExecutorChannel with a Spring-managed executor
Buffer bursts for a slower consumerQueueChannel with a capacity, read by a poller
Several independent reactions to one eventPublishSubscribeChannel
Plain Java code entering a flowA gateway interface
Parallel processing of the parts of a requestsplit, an executor channel, then aggregate with a groupTimeout
A fallback answer instead of an exceptionAn error channel on the gateway
Failures in asynchronous flowsA flow subscribed to errorChannel

For a single in-process event with a few listeners, Spring's own application events are simpler; Spring Integration earns its place when a process has several steps, threads or external systems. To schedule plain methods without a flow, see Spring scheduling, and for messaging through a broker, Spring Kafka.