SimpleRabbitListenerContainerFactory的MethodInterceptor能否接收@RabbitListener的POJO参数?
问题解答
不能把参数强转为Message,但可以直接强转为NewBarcodes,具体原因和说明如下:
- 你的配置中,
Jackson2JsonMessageConverter会在调用@RabbitListener标注的方法前,完成RabbitMQ原始消息到NewBarcodesPOJO的转换。 - 自定义
MethodInterceptor属于SimpleRabbitListenerContainerFactory的adviceChain,它的拦截时机是消息转换完成后、目标监听方法执行前。此时invoke方法的参数数组里,对应监听方法的入参已经是转换后的NewBarcodes对象,而非原始的Message实例。 - 如果强行转成
Message会抛出类型转换异常,因为参数类型已经是NewBarcodes。
举个实际代码示例:
public class TrackNewBarcode implements MethodInterceptor { @Override public Object invoke(MethodInvocation invocation) throws Throwable { // 直接获取并强转为NewBarcodes NewBarcodes barcodes = (NewBarcodes) invocation.getArguments()[0]; // 执行自定义追踪逻辑 processTrack(barcodes); // 继续执行目标监听方法 return invocation.proceed(); } private void processTrack(NewBarcodes barcodes) { // 这里写你的追踪处理代码 } }
额外注意:
- 要确保
@RabbitListener方法的入参确实只有NewBarcodes这一个参数,或者能准确找到对应参数的索引位置。 - 如果监听方法有多个参数,需要根据实际参数顺序定位到
NewBarcodes实例。
内容的提问来源于stack exchange,提问作者Kode Charlie
相关产品推荐
相关产品推荐

