跳到主要内容

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

QWen Plus 中英对照 Service Activators and the .handle() method Service Activators and the .handle() method

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

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

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

然而,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();
}
java

我们也可以在 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();
}
java