Spring Boot WebFlux整合Reactive MongoDB报POJO无构造方法实例化错误
问题排查与解决步骤
1. 优先检查Lombok注解处理器配置
当前你的Gradle依赖中仅声明了Lombok的implementation依赖,缺少编译时注解处理器配置,会导致@NoArgsConstructor、@Data等注解不会实际生成对应的构造器、存取方法,是该报错的最常见诱因。在dependencies代码块中补充以下配置即可:
annotationProcessor 'org.projectlombok:lombok:1.18.20'
配置完成后重新编译项目,检查编译后的Transit class文件是否存在public无参构造方法。
2. 显式指定持久化构造器
你在POJO中手动定义了两个自定义有参构造,会导致Spring Data MongoDB的构造器解析逻辑优先匹配有参构造,跳过无参构造。你可以在无参构造上添加@PersistenceConstructor注解,强制Spring Data使用该构造器完成文档反序列化的实例化操作:
@Document @Data @AllArgsConstructor @NoArgsConstructor public class Transit { @Id private String id; private String planetName; private Double decimal; @Field(targetType = FieldType.INT64) private Long epochSeconds; private String key; private Double speed; @PersistenceConstructor public Transit() { } public Transit(String planetName) { this.planetName = planetName; } public Transit(String planetName, String key) { this.planetName = planetName; this.key = key; } }
同时为epochSeconds字段添加@Field注解显式指定类型映射,避免MongoDB的$numberLong类型解析异常。
3. 统一Spring Boot依赖版本
当前配置中spring-boot-starter-data-mongodb-reactive的版本为2.5.3,与其他Spring Boot Starter的2.5.4版本不一致,可能存在依赖冲突。你可以去掉该依赖的显式版本声明,由Spring Boot依赖管理插件统一管控版本:
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb-reactive'
兼容性说明
Spring Boot 2.5.x对应的Spring Data MongoDB 3.2.x版本完全兼容MongoDB 5.0,你遇到的问题属于POJO配置与Lombok依赖配置问题,与数据库版本无关。
内容的提问来源于stack exchange,提问作者abg
相关产品推荐
相关产品推荐

