Spring Integration XML 配置需显式声明通道与端点并严格绑定,自定义通道必须预先定义,splitter/router/service-activator 等组件需匹配方法签名与消息头,aggregator 依赖 sequence 和 correlation 机制,error-channel 全局复用易致异常静默。

Spring Integration XML 是一种基于 Spring 命名空间的配置方式,用来声明消息通道(channel)、端点(splitter、router、service-activator 等)和连接关系。它不是“过时写法”,而是在需要显式控制生命周期、调试可见性高、或与遗留 XML 配置共存的场景中依然实用的选择。
XML 配置的核心结构:从 channel 到 endpoint 的链路必须显式声明
XML 不像 Java DSL 或注解那样靠扫描自动连线,每个组件都得手动 <int:xxx> 定义,并用 input-channel / output-channel 显式绑定。漏一个 channel 名拼错、少一个 ref,启动就报 BeanCreationException: No bean named 'xxxChannel' is defined。
- 所有自定义
channel必须先定义(哪怕只是<int:channel id="firstChannel"/>),否则后续端点无法引用 -
gateway接口方法上加@Gateway(requestChannel = "firstChannel"),但 XML 里仍需有对应<int:channel id="firstChannel"/>,否则运行时报错 - 若用
<int:publish-subscribe-channel>,消费者必须是线程安全的;用<int:queue-channel>则需配task-executor否则默认单线程阻塞
splitter + router + service-activator 的典型 XML 写法
比如把一个订单拆成多个咖啡项,再按冷热路由,最后统一聚合——这种 EIP 流程在 XML 中非常直观,但要注意「输出通道」必须和下一个组件的「输入通道」严格一致:
<!-- 拆分器:把 Order 拆成多个 Cafe -->
<int:splitter input-channel="firstChannel" output-channel="secondChannel"
ref="orderSplitter" method="split"/>
<p><!-- 路由器:根据 cafe.temperature 返回 coldChannel 或 hotChannel -->
<int:router input-channel="secondChannel" ref="cafeRouter" method="route"/></p><p><!-- 两个服务激活器分别消费 coldChannel 和 hotChannel -->
<int:service-activator input-channel="coldChannel" ref="coldHandler" method="make"/>
<int:service-activator input-channel="hotChannel" ref="hotHandler" method="make"/></p><p><!-- 所有处理完的消息都发到 fourthChannel -->
<int:channel id="fourthChannel"/>-
ref指向的 bean 必须是 Spring 管理的(@Component或 XML 中定义),且方法签名要匹配:public List<Cafe> split(Order order)、public String route(Cafe cafe) - router 方法返回值必须是
String(通道 ID)或MessageChannel实例,不能返回void或任意对象 - 如果
service-activator方法返回非void,返回值会自动封装为新消息发往output-channel;没配则默认丢弃
aggregator 容易踩的三个坑
聚合器依赖消息头(如 correlationId、sequenceNumber)做分组合并,XML 中不显式设置就几乎必然失败:
- splitter 必须开启
apply-sequence="true",否则aggregator收不到序列信息,无法判断哪些消息属于同一批 - aggregator 默认只等 1 秒就释放未完成组,要用
send-timeout="5000"或expire-groups-upon-completion-timeout="true"控制超时 - completion-strategy 必须指定类+方法,例如:
completion-strategy="com.example.CafeAggregationStrategy" completion-strategy-method="isComplete",且该类要实现ReleaseStrategy
XML 方式真正的难点不在语法,而在消息头传递是否完整、channel 生命周期是否被意外复用、以及错误通道(error-channel)是否被全局覆盖。哪怕一个 <int:channel id="errorChannel"> 定义在别处,就可能让所有端点的异常静默吞掉。










