- Chapter
- Chapter 1 — Spring Integration
- Prerequisites
- Volumes I–II (Spring container, AOP)
- You will be able to
- Explain the messaging model behind Spring Integration, choose channel types, build endpoints and integration flows, and connect external systems through adapters and gateways
- Covers
- Messaging · Channels · Endpoints · Adapters
On this page
- 1. Concept / Definition
- 2. Why It Exists
- 3. Core Concepts
- 4. How It Works Internally
- 4A. Deep Dive — Error Handling and Transactions in Flows
- 5. APIs / Features / Syntax
- 6. Practical Examples
- 7. Common Problems & Mistakes
- 8. Performance & Production Considerations
- 9. Architecture & Design Considerations
- 10. Interview Questions & Answers
1Concept / Definition
Enterprise integration connects independent applications so they can exchange data and trigger behaviour without being tightly coupled. Messaging is its dominant style: systems exchange messages through channels, processed by endpoints, with adapters bridging to external technologies. Spring Integration implements this model inside a Spring application, following the Enterprise Integration Patterns catalogue.

| Building block | Spring Integration type | Role |
|---|---|---|
| Message | Message<T> (GenericMessage), MessageHeaders | Payload + metadata, immutable |
| Channel | MessageChannel (DirectChannel, QueueChannel, PublishSubscribeChannel, ExecutorChannel) | Pipe between components |
| Endpoint | Service activator, transformer, router, filter, splitter, aggregator | Processing step |
| Adapter | Inbound/outbound channel adapters (file, HTTP, JMS, AMQP, Kafka, JDBC, FTP, …) | Connection to external systems |
| Gateway | @MessagingGateway interface | Entry point hiding messaging from Java callers |
2Why It Exists
Point-to-point integrations written by hand — a file poller here, an HTTP client there, a JMS listener elsewhere — duplicate plumbing, mix transport code with business logic and are hard to change. EIP (Hohpe & Woolf, 2003) gave integration a shared vocabulary; Spring Integration (2007) made those patterns first-class Spring components with dozens of adapters, so that integrations become declarative, testable flows instead of scattered infrastructure code.
3Core Concepts
3.1 Messaging
| Header | Meaning |
|---|---|
id, timestamp | Unique message identity and creation time |
correlationId | Relates messages (e.g. split parts to the original) |
replyChannel, errorChannel | Where replies/errors go |
sequenceNumber, sequenceSize | Position within a split group |
| Custom headers | Tenant, trace context, content type, business keys |
Message<Order> message = MessageBuilder.withPayload(order)
.setHeader("tenant", "eu-1")
.setHeader(MessageHeaders.CONTENT_TYPE, "application/json")
.build();3.2 Channels

| Channel | Semantics | Threading |
|---|---|---|
DirectChannel (default) | Point-to-point, one subscriber handles each message | Caller's thread (transaction continues) |
QueueChannel | Buffers messages; consumers poll | Poller threads |
PublishSubscribeChannel | Broadcast to all subscribers | Caller's thread or executor |
ExecutorChannel | Point-to-point, handoff to executor | Executor (e.g. virtual threads) |
FluxMessageChannel | Reactive streams | Reactor scheduling |
3.3 Endpoints

@Bean
IntegrationFlow orderFlow(OrderService orders) {
return IntegrationFlow.from("incomingOrders") // input channel
.filter(Order.class, Order::isValid) // filter endpoint
.transform(Order.class, OrderMapper::toCommand) // transformer
.handle(orders, "place") // service activator
.get();
}3.4 Adapters

@MessagingGateway(defaultRequestChannel = "incomingOrders")
public interface OrderGateway {
void submit(Order order); // callers see a Java interface, not messaging
}
@Bean
IntegrationFlow sftpImport(SessionFactory<SftpClient.DirEntry> sftp) {
return IntegrationFlow
.from(Sftp.inboundAdapter(sftp)
.remoteDirectory("/outbox/orders")
.localDirectory(new File("/tmp/orders")),
e -> e.poller(Pollers.fixedDelay(Duration.ofMinutes(1))))
.transform(Files.toStringTransformer())
.split(new CsvOrderSplitter())
.channel("incomingOrders")
.get();
}4How It Works Internally
1. Flow definitions (Java DSL or annotations) register channels and endpoints as beans; IntegrationFlow beans are processed by the integration infrastructure at startup.
2. Event-driven endpoints subscribe to SubscribableChannels; polling endpoints use a Poller (trigger, max messages, transaction) to receive from PollableChannels or external sources.
3. Sending to a DirectChannel invokes the subscriber synchronously on the same thread — the whole flow may run in one transaction.
4. Handlers (MessageHandlers) wrap your beans: arguments are resolved from payload/headers (@Payload, @Header), return values become new messages with copied headers.
5. Exceptions propagate to the caller (direct channels) or go to the errorChannel (async flows), where error flows can log, retry or dead-letter.
4ADeep Dive — Error Handling and Transactions in Flows
@Bean
IntegrationFlow paymentFlow(PaymentService payments) {
return IntegrationFlow
.from(Kafka.messageDrivenChannelAdapter(consumerFactory(), "payments")
.errorChannel("paymentErrors"))
.handle(payments, "apply",
e -> e.advice(retryAdvice()) // retry transient errors
.transactional(transactionManager)) // DB tx around handler
.get();
}
@Bean
IntegrationFlow paymentErrorFlow() {
return IntegrationFlow.from("paymentErrors")
.handle(m -> log.error("payment failed: {}", m.getPayload()))
.get();
}
@Bean
RequestHandlerRetryAdvice retryAdvice() {
var advice = new RequestHandlerRetryAdvice();
advice.setRecoveryCallback(new ErrorMessageSendingRecoverer(deadLetterChannel()));
return advice;
}| Concern | Mechanism |
|---|---|
| Synchronous flow errors | Exceptions propagate to the caller/adapter (e.g. message redelivery) |
| Asynchronous errors | errorChannel header or global errorChannel |
| Retry per endpoint | RequestHandlerRetryAdvice (with backoff) |
| Transactions | .transactional() on handlers or pollers; direct channels share the transaction |
| Dead-lettering | Recoverer sending to a DLQ channel/adapter |
5APIs / Features / Syntax
| API | Purpose |
|---|---|
spring-boot-starter-integration | Spring Integration auto-configuration |
IntegrationFlow.from(...), .filter, .transform, .route, .split, .aggregate, .handle, .channel | Java DSL |
@ServiceActivator, @Transformer, @Router, @Filter, @Splitter, @Aggregator | Annotation style |
MessageChannels.direct()/queue()/publishSubscribe()/executor() | Channel factories |
@MessagingGateway | Gateways |
Adapter modules (spring-integration-file, -sftp, -http, -jms, -amqp, -kafka, -jdbc) | External systems |
@EnableIntegrationManagement, Micrometer integration | Metrics |
6Practical Examples
6.1 Direct vs executor channel
@Bean
MessageChannel incomingOrders() {
return MessageChannels.direct().getObject(); // same thread, same tx
}
@Bean
MessageChannel notifications() {
return MessageChannels.executor(Executors.newVirtualThreadPerTaskExecutor())
.getObject();
}6.2 HTTP inbound gateway
@Bean
IntegrationFlow httpOrders() {
return IntegrationFlow.from(Http.inboundGateway("/integration/orders")
.requestMapping(m -> m.methods(HttpMethod.POST))
.requestPayloadType(Order.class))
.channel("incomingOrders")
.get();
}6.3 Testing a flow
@SpringBootTest
class OrderFlowTest {
@Autowired OrderGateway gateway;
@MockitoBean OrderService orders;
@Test
void invalidOrdersAreFiltered() {
gateway.submit(Order.invalid());
verifyNoInteractions(orders);
}
}6.4 Integration styles compared
| Style | Coupling | Example |
|---|---|---|
| File transfer | Low, batch-oriented | Partner CSV via SFTP |
| Shared database | High | Two apps on the same tables (avoid) |
| Remote procedure call | Temporal coupling | REST, gRPC |
| Messaging | Low, asynchronous | Events on Kafka, commands on RabbitMQ |
6.5 When to use Spring Integration
| Situation | Recommendation |
|---|---|
| Multi-step flows with many protocols (SFTP, HTTP, JMS, DB) | Spring Integration |
| Simple consume-process-produce with one broker | Plain @KafkaListener/@RabbitListener or Spring Cloud Stream |
| Broker-agnostic event-driven microservices | Spring Cloud Stream (functions + binders) |
| Heavy transformation, mapping UIs, many partners | Dedicated integration platform (iPaaS) |
7Common Problems & Mistakes
- Business logic inside flow lambdas instead of services.
- Unintended thread handoffs losing transactions or messages.
- No error channel handling for asynchronous flows.
- Huge flows that nobody can reason about.
- Using Spring Integration for trivial single-listener cases.
- Unbounded queue channels causing memory growth.
8Performance & Production Considerations
| Concern | Guidance |
|---|---|
| Throughput | Direct channels are cheap; executor channels add parallelism |
| Back-pressure | Bounded queues, poller max messages |
| Observability | Integration metrics (channel send/receive), tracing via message headers |
| Management | Control bus, flow start/stop, graceful shutdown of pollers |
9Architecture & Design Considerations
- Integration at the edges: flows adapt external protocols to domain services.
- Canonical internal messages vs per-partner formats transformed at adapters.
- Durable handoffs (brokers) between services, in-memory channels within one.
- Choose the lightest tool that handles the integration's complexity.
10Interview Questions & Answers
What is a message in Spring Integration?
In Spring Integration, a message is the unit of data that flows between components. It is an immutable object of type Message<T> with two parts: a payload, which is the data itself, such as an Order or a String, and headers, which carry metadata such as an ID, a timestamp, a correlation ID, a reply channel or content type. Because messages are immutable, components never change a message in place; they create a new one, for example with MessageBuilder. Keeping data and metadata together lets routers, filters and transformers make decisions without knowing anything about where the message came from.
What is a message channel?
A message channel is the pipe that connects components in a Spring Integration flow. A producer sends a message to a channel without knowing who will consume it, and consumers subscribe to or poll the channel without knowing who produced it, which decouples the two sides. Different channel types give different behaviour: a direct channel hands the message to one subscriber on the sender's thread, a queue channel buffers messages for consumers on other threads, and a publish-subscribe channel delivers a copy to every subscriber. Choosing the channel type is how you control threading, buffering and fan-out in a flow.
What is the difference between a DirectChannel and a QueueChannel?
A DirectChannel delivers each message immediately to a single subscriber, calling it on the sender's thread. The send completes when the subscriber has finished, so the flow behaves like a method call: exceptions propagate back to the sender, and the sender's transaction covers the work. A QueueChannel stores messages in a queue, and a separate poller on other threads takes them out and processes them. The sender returns as soon as the message is queued, which decouples timing and smooths bursts, but transactions do not carry across and the queue must be sized carefully, because an in-memory queue loses messages if the application stops.
What is a channel adapter?
A channel adapter connects a message channel to something outside the integration flow, such as a file system, a JMS queue, a Kafka topic, an FTP server, a database or an HTTP endpoint. An inbound channel adapter receives data from the external system, for example by polling a directory or listening to a queue, wraps it in a message and sends it to a channel. An outbound channel adapter takes messages from a channel and writes them to the external system, for example as a file or a REST call. Adapters are one-way; for request-reply interactions, Spring Integration uses gateways.
How do you handle errors in asynchronous flows?
In asynchronous flows, an exception cannot simply propagate back to the original sender, because the sender's thread has moved on. Spring Integration therefore wraps the failure in an ErrorMessage, containing the exception and the failed message, and sends it to an error channel: either one configured on the flow or the default errorChannel bean. You build an error-handling flow on that channel, for example to log the failure with its correlation ID, retry with back-off, route the original message to a dead-letter destination for manual handling or send an alert. Retry advice can also be attached directly to individual endpoints.
What is a messaging gateway?
A messaging gateway is a plain Java interface whose implementation Spring Integration generates. Calling a method on it, for example orderGateway.submit(order), creates a message from the arguments, sends it into a flow, and, if the method has a return type, waits for a reply message and returns its payload. Callers simply use an interface and never see channels or the messaging API. This keeps business code independent of the integration technology, makes it easy to test with a mock gateway and lets the flow behind it change, for example from synchronous to queued, without changing callers.
When would you choose Spring Integration over plain listeners?
Spring Integration earns its place when a flow combines several enterprise integration patterns: receiving from one protocol and sending to another, transforming formats, routing by content, splitting and aggregating, filtering and handling errors and retries along the way. Integrations with partners and legacy systems, such as picking up files from SFTP, transforming them and sending them to several internal queues, are typical examples. For simple cases, such as one service consuming events from one broker, a plain @KafkaListener or @RabbitListener, or Spring Cloud Stream, is easier to read and maintain. Choose the lightest tool that handles the flow's real complexity.
How does Spring Integration fit into a microservice architecture?
Spring Integration fits best at the edges of a microservice architecture, where services meet partners, file-based exchanges and legacy systems with their own protocols and formats. There it acts as an anti-corruption layer: it receives external data, validates and transforms it, and publishes clean domain events or commands to the internal messaging platform. Between microservices themselves, durable brokers such as Kafka or RabbitMQ with simple listeners are usually enough. Business logic should stay in plain services called by the flow, not inside transformers and routers, so the integration layer stays replaceable and the domain stays testable.
Test your knowledge on this topic →Flashcards from this topic's 8 questions, filtered by level and type.