跳到主要内容
版本:7.0.2

服务激活器与 .handle() 方法

DeepSeek V3 中英对照 Service Activators and the .handle() method Service Activators and the .handle() method

.handle() EIP 方法的目标是调用任何 MessageHandler 实现或某个 POJO 上的任何方法。另一种选择是使用 lambda 表达式定义“活动”。因此,我们引入了一个通用的 GenericHandler<P> 函数式接口。它的 handle 方法需要两个参数:P payloadMessageHeaders headers(从版本 5.1 开始)。基于此,我们可以如下定义一个流程:

@Bean
public IntegrationFlow myFlow() {
return IntegrationFlow.from("flow3Input")
.<Integer>handle((p, h) -> p * 2)
.get();
}

前面的例子会将接收到的任何整数翻倍。

然而,Spring Integration 的一个主要目标是通过运行时类型转换实现松耦合,即将消息负载转换为消息处理器的目标参数。由于 Java 不支持 lambda 类的泛型类型解析,我们为大多数 EIP 方法和 LambdaMessageProcessor 引入了一个变通方案,即添加一个额外的 payloadType 参数。这样做可以将繁重的转换工作委托给 Spring 的 ConversionService,该服务使用提供的 type 和请求的消息来匹配目标方法参数。以下示例展示了最终的 IntegrationFlow 可能的样子:

@Bean
public IntegrationFlow integerFlow() {
return IntegrationFlow.from("input")
.<byte[], String>transform(p - > new String(p, "UTF-8"))
.handle(Integer.class, (p, h) -> p * 2)
.get();
}

我们也可以在 ConversionService 中注册一些 BytesToIntegerConverter 来省去额外的 .transform() 调用:

@Bean
@IntegrationConverter
public BytesToIntegerConverter bytesToIntegerConverter() {
return new BytesToIntegerConverter();
}

@Bean
public IntegrationFlow integerFlow() {
return IntegrationFlow.from("input")
.handle(Integer.class, (p, h) -> p * 2)
.get();
}