返回

SpringBoot多模块install报依赖模块包找不到?别再愁眉苦脸了,请看解决之道!

后端

SpringBoot 多模块项目:依赖模块找不到时的解决方法

引言

在构建多模块 SpringBoot 项目时,你可能会遇到一个棘手的错误,提示无法找到依赖模块的包。本文将深入探讨这个问题的根源,并提供一种简单有效的解决方法。

问题

当执行 mvn install 命令时,你可能会遇到以下错误提示:

[ERROR] Failed to execute goal on project module-a: Could not resolve dependencies for project com.example:module-a:jar:0.0.1-SNAPSHOT: Failure to find com.example:module-b:jar:0.0.1-SNAPSHOT in https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced -> [Help 1]

问题根源

此错误的根源在于 SpringBoot 项目打包方式。SpringBoot 会生成两个 jar 包:一个普通的可引用 jar 包和一个 SpringBoot 可执行 jar 包。当可执行 jar 包生成后,它会覆盖普通的 jar 包,导致依赖模块无法找到它。

解决方案:添加分类器

为了解决这个问题,我们需要在被依赖模块的打包插件 <configuration> 中添加 <classifier> 元素。以下是步骤指南:

  1. 打开被依赖模块的 pom.xml 文件。
  2. <build> 元素中找到 <plugins> 元素。
  3. <plugins> 元素中添加 <plugin> 元素。
  4. <plugin> 元素中添加 <groupId> 元素,值为 org.apache.maven.plugins
  5. <plugin> 元素中添加 <artifactId> 元素,值为 maven-jar-plugin
  6. <plugin> 元素中添加 <configuration> 元素。
  7. <configuration> 元素中添加 <classifier> 元素,值为 sources
  8. 保存 pom.xml 文件。

代码示例

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <configuration>
        <classifier>sources</classifier>
    </configuration>
</plugin>

注意事项

  • <classifier> 元素只能添加到被依赖模块的 pom.xml 文件中。
  • <classifier> 元素的值可以任意指定,但最好使用有意义的名称,以便于区分不同的 jar 包。
  • 添加 <classifier> 元素后,需要重新执行 mvn install 命令。

结论

通过在被依赖模块的 pom.xml 文件中添加 <classifier> 元素,我们可以轻松解决 SpringBoot 多模块项目中依赖模块包找不到的常见问题。这种方法既简单又有效,让你可以顺利构建和安装项目。

常见问题解答

  1. 为什么需要 <classifier> 元素?

    • <classifier> 元素给生成的 jar 包添加了一个分类器,这样依赖模块就可以通过该分类器指定要引用的 jar 包。
  2. 我可以为 <classifier> 元素使用什么值?

    • <classifier> 元素的值可以任意指定,但最好使用有意义的名称,以便于区分不同的 jar 包。
  3. 是否可以将 <classifier> 元素添加到依赖模块的 pom.xml 文件中?

    • 不,<classifier> 元素只能添加到被依赖模块的 pom.xml 文件中。
  4. 除了添加 <classifier> 元素之外,还有什么其他解决方法吗?

    • 没有其他直接的方法来解决这个问题。但是,你可以尝试使用不同的打包策略或使用其他依赖管理工具。
  5. 我仍然遇到相同的问题。我该怎么办?

    • 请仔细检查你的 pom.xml 文件是否正确配置,并且已添加 <classifier> 元素。如果你仍然遇到问题,可以在相关论坛或社区寻求帮助。