【问题标题】:Maven nested dependency is not accessible无法访问 Maven 嵌套依赖项
【发布时间】:2020-02-11 08:30:28
【问题描述】:

我有一个 maven 项目,在父 POM 中,我在这个父 POM 中声明了一些依赖项。这个 POM 在子 POM 中使用,如代码 sn-p 所示。在编译 Child 项目时,IntelliJ 抱怨找不到父项目中使用的接口。该接口在父 POM 的依赖项“anotherApp”中声明。

我对 Maven 依赖项的理解是,由于我在 Parent POM 中声明了依赖项,它也应该在子 POM 中继承,并且子应该能够毫无问题地访问这些依赖项及其类/接口。

我尝试在父 POM 中的 dependencyManagement 标记中添加依赖项。但无法达到我期望得到的。我还查看了父项目和子项目的依赖关系树。在 parent 中,依赖树显示 anotherApp 作为其依赖项,但在 child 中,仅显示 parent 作为依赖项,anotherApp 不显示为依赖项来自 parent。

这就是我的父 POM 的样子

<project>
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>it.app</groupId>
    <artifactId>commonParent</artifactId>
    <version>1.0-SNAPSHOT</version>
    <relativePath>../CommonParent/pom.xml</relativePath>
  </parent>

  <groupId>com.app</groupId>
  <artifactId>parent</artifactId>
  <version>0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <dependencies>
      <dependency>
          <groupId>com.myapp</groupId>
          <artifactId>anotherApp</artifactId>
          <version>2.0-SNAPSHOT</version>
      </dependency>
  </dependencies>
</project>

这就是我的孩子 POM 的样子

<project>
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>it.app</groupId>
    <artifactId>commonParent</artifactId>
    <version>1.0-SNAPSHOT</version>
    <relativePath>../CommonParent/pom.xml</relativePath>
  </parent>

  <groupId>com.app</groupId>
  <artifactId>child</artifactId>
  <version>0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <dependencies>
      <dependency>
          <groupId>com.app</groupId>
          <artifactId>parent</artifactId>
      </dependency>
  </dependencies>
</project>

在“anotherApp”中声明了一个接口 Foo。父项目可以访问此接口。但子项目无法访问该接口。 IntelliJ 抱怨它无法访问这个接口。

【问题讨论】:

    标签: java maven intellij-idea dependencies


    【解决方案1】:

    需要纠正的两点:

    • 父 POM 应该有 &lt;packaging&gt;pom&lt;/packaging&gt;
    • 子项目应该使用父POM作为依赖,而是将其添加到&lt;parent&gt;标签中。

    【讨论】:

    • 我不能这样做,因为我需要父母绑定到一个罐子里,而孩子已经有了另一个父母。您能否告诉我是否有办法将父 pom 中添加的依赖项添加到子项目中。 IntelliJ 建议将“anotherApp”依赖项添加到子项,但我希望它通过父项,因为我已经将父项添加为子项的依赖项
    • 我已经通过代码 sn-p 进行了编辑,以便您更好地了解这个问题
    • 称它为“父”和“子”具有误导性,因为您的“父”实际上是“子”的依赖项。由于传递依赖解析,Maven 也会找到依赖“anotherApp”。通常,您也可以访问其内容,但有几个原因可能不是这种情况(例如,您将范围设置为运行时、测试或在 dependencyManagement 中提供或 IntelliJ 与项目不是最新的)。请考虑:如果您直接在源代码中使用类/接口,则应将相关的 jar 添加为直接依赖项(而不是传递依赖它)。
    猜你喜欢
    • 2018-06-14
    • 2018-10-24
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 2011-11-27
    • 2012-01-12
    • 2013-05-22
    • 2020-07-06
    相关资源
    最近更新 更多