You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot整合MongoDB启动报错:UnsatisfiedDependencyException求助

问题排查与解决方案

核心错误原因

从报错栈最底层可以定位到关键问题:

java.lang.ClassNotFoundException: com/mongodb/internal/connection/StreamFactory

这说明MongoDB驱动相关类缺失或版本与Spring Boot不兼容,导致无法创建MongoClient实例,进而引发一系列依赖注入失败的连锁错误。

解决方案

1. 修正依赖配置,使用Spring Boot官方Starter

不要直接引入mongodb-driver-sync,改用Spring Boot提供的spring-boot-starter-data-mongodb,它会自动管理所有兼容的依赖版本,彻底避免版本冲突问题。

Maven配置(pom.xml)

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

移除项目中直接引入的mongodb-driver-sync相关依赖。

Gradle配置(build.gradle)

implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'

同样移除手动添加的MongoDB驱动依赖。

2. 清理依赖缓存并重新构建

如果是依赖缓存损坏导致的类缺失,执行以下操作强制刷新依赖:

  • Maven:mvn clean install -U
  • Gradle:gradle clean build --refresh-dependencies

3. 版本兼容性校验(可选)

Spring Boot 3.2.x对应的MongoDB驱动兼容版本为4.10.x及以上,如果必须手动指定版本,确保两者版本匹配,避免跨大版本的兼容性问题。

额外潜在问题提醒

你的Restaurant类中存在初始化空指针风险:

private double restaurantRating = firstRating.restaurantRating + secondRating.restaurantRating;

当firstRating或secondRating为null时,启动服务或创建对象会抛出NullPointerException。建议改用@PostConstruct方法计算:

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = "restaurants")
public class Restaurant {
    @Id
    private String id;
    private String name;
    private String address;
    private String city;
    private String country;
    private Rating firstRating;
    private Rating secondRating;
    private double restaurantRating;

    @PostConstruct
    private void calculateRestaurantRating() {
        double rating1 = firstRating != null ? firstRating.getRestaurantRating() : 0;
        double rating2 = secondRating != null ? secondRating.getRestaurantRating() : 0;
        this.restaurantRating = rating1 + rating2;
    }
}

内容的提问来源于stack exchange,提问作者luchenzo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 02:24:49