Spring Cloud Stream JSON转POJO失败求助:配置后仍触发异常
问题:Spring Cloud Stream无法自动将JSON转换为POJO
Spring Cloud Stream官方文档明确说明框架具备自动将JSON消息负载转换为POJO的能力,但我按照文档示例实现后始终失败,具体情况如下:
消费者代码
@SpringBootApplication public class LoggingConsumerApplication { public static void main(String[] args) { SpringApplication.run(LoggingConsumerApplication.class, args); } @Bean public Consumer<Person> exampleEventConsumer() { return person -> { System.out.println("Received: " + person); }; } public static class Person { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public String toString() { return this.name; } } }
配置文件(application.yaml)
spring: cloud: function: definition: exampleEventConsumer stream: bindings: exampleEventConsumer-in-0: destination: try-me binders: solace-broker: type: solace environment: solace: java: host: "tcp://mr-connection-zw285jhb96b.messaging.solace.cloud:55555" msgVpn: "msgvpn-example" clientUsername: "solace-cloud-client" clientPassword: "p2tkutqaru4pss6t9s0"
触发的错误信息
2024-04-15T22:48:45.493-04:00 ERROR 44014 --- [HelloWorldSpringCloudStream] [pool-3-thread-1] o.s.integration.handler.LoggingHandler : org.springframework.messaging.MessageHandlingException: error occurred in message handler [org.springframework.cloud.stream.function.FunctionConfiguration$FunctionToDestinationBinder$1@5fe7e7e5], failedMessage=GenericMessage [payload={"name":"Miles Archer"}, headers={solace_expiration=0, solace_destination=try-me, solace_replicationGroupMessageId=rmid1:30704-81ae9045b12-00000000-00000146, deliveryAttempt=3, solace_isReply=false, solace_timeToLive=0, solace_receiveTimestamp=0, acknowledgmentCallback=com.solace.spring.cloud.stream.binder.inbound.acknowledge.JCSMPAcknowledgementCallback@19dc7076, solace_discardIndication=false, solace_dmqEligible=false, solace_priority=-1, solace_redelivered=false, id=61619594-f32e-a2a9-3738-baea97e80635, contentType=application/json, timestamp=1713235722421}]
官方文档说明
此方式可体现框架核心特性:自动尝试将入站消息负载转换为Person类型。
我多次尝试均无法解决,求指导遗漏的配置或步骤!
排查与解决方案
- 确认Jackson依赖存在:确保项目中包含
com.fasterxml.jackson.core:jackson-databind,Spring Boot starter通常会自动引入,但如果是手动管理依赖,需检查是否缺失。 - 检查Person类构造函数:若后续给Person类添加了带参构造,必须显式声明无参构造,否则Jackson无法实例化对象;当前代码中Java会自动生成默认无参构造,此点可忽略,但需注意后续修改。
- 验证消息Content-Type:即使消息内容是JSON,若Solace发送时未将
content-type设置为application/json(比如默认是text/plain),Spring Cloud Stream不会触发JSON转换,需在发送工具中明确设置该属性。 - 显式配置JSON消息转换器:添加配置类强制启用Jackson转换逻辑:
@Configuration public class StreamMessageConverterConfig { @Bean public MappingJackson2MessageConverter jacksonMessageConverter() { return new MappingJackson2MessageConverter(); } }
- 检查版本兼容性:确保Solace Binder版本与Spring Cloud Stream版本匹配,版本不兼容可能导致转换逻辑异常,可参考官方适配文档调整依赖版本。
- 开启调试日志:添加日志配置查看转换细节,定位具体错误:
logging: level: org.springframework.messaging.converter: DEBUG org.springframework.cloud.stream: DEBUG
通过调试日志可获取更详细的转换失败原因,比如字段不匹配、序列化/反序列化异常等。
内容的提问来源于stack exchange,提问作者Dakotah North
相关产品推荐
相关产品推荐

