解决无法引入 mysql-connector-j 的问题

开发环境

  • Windows 10
  • Oracle JDK 1.8
  • Maven 3.8.8
  • IntelliJ IDEA 2022.2.2

问题

在使用 Spring initializr 创建 Spring Boot 项目时,无法引入 mysql-connector-j 这个依赖,报错信息:

com.mysql:mysql-connector-j:jar:unknown was not found in https://maven.aliyun.com/repository/public during a previous attempt. This failure was cached in the local repository and resolution is not reattempted until the update interval of aliyunmaven has elapsed or updates are forced

pom.xml 文件

// 父依赖
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.14</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.0.32</version>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.5.3.1</version>
    </dependency>
</dependencies>

原因

我使用的 Spring Boot 版本为 2.5.14,该版本使用的 mysql-connector-j 版本为 8.0.29,同时我的依赖是从阿里云的镜像库而不是 Maven 的中央仓库上下载的。我尝试手动引入这个版本。

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.0.29</version>
    <scope>runtime</scope>
</dependency>

结果报了同样的错误。也就是说,阿里云镜像仓库可能没有这个版本的 mysql-connector-j

解决方法

手动引入高于 8.0.29 版本的 mysql-connector-j 即可解决。

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.0.32</version>
    <scope>runtime</scope>
</dependency>