如何在没有版本标签的情况下定义 Maven 依赖?

MD.*_*oob 6 dependencies pom.xml maven

我有一个没有在 pom 中定义依赖版本的 pom 工作正常,另一个没有依赖版本的 pom 不起作用。

一个有效的:

<project>
    <parent>
        <artifactId>artifact-parent</artifactId>
        <groupId>group-parent</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>group-a</groupId>
            <artifactId>artifact-a</artifactId>
        </dependency>
        <dependency>
            <groupId>group-a</groupId>
            <artifactId>artifact-b</artifactId>
        </dependency>
    </dependencies>
</project>
Run Code Online (Sandbox Code Playgroud)

这个不起作用:

<project>
    <dependencies>
        <dependency>
            <groupId>group-a</groupId>
            <artifactId>artifact-a</artifactId>
        </dependency>
        <dependency>
            <groupId>group-a</groupId>
            <artifactId>artifact-b</artifactId>
        </dependency>
    </dependencies>
</project>
Run Code Online (Sandbox Code Playgroud)

这两者的唯一不同似乎是:

<parent>
    <artifactId>artifact-parent</artifactId>
    <groupId>group-parent</groupId>
    <version>1.0-SNAPSHOT</version>
</parent>
Run Code Online (Sandbox Code Playgroud)

第二个不起作用对我来说似乎很好,但我的问题是为什么第一个起作用?

引用自maven pom 参考

这个三位一体代表了特定项目在时间上的坐标,将其划定为该项目的一个依赖项。

所以我的问题是第一个是如何工作的?

MD.*_*oob 5

这里要注意的主要事情是:

<parent>
    <artifactId>artifact-parent</artifactId>
    <groupId>group-parent</groupId>
    <version>1.0-SNAPSHOT</version>
</parent>
Run Code Online (Sandbox Code Playgroud)

依赖的版本看起来像是在父 pom 中定义的。这可能是这样的:

<project>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>group-a</groupId>
                <artifactId>artifact-a</artifactId>
                <version>1.0</version>
            </dependency>
            <dependency>
                <groupId>group-a</groupId>
                <artifactId>artifact-b</artifactId>
                <version>1.0</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>
Run Code Online (Sandbox Code Playgroud)

再次引用文档

This is because the minimal set of information for matching a dependency reference against a dependencyManagement section is actually {groupId, artifactId, type, classifier}.

这里我们不需要定义,{type, classifier}因为它与默认值相同,如下所示:

<type>jar</type>
<classifier><!-- no value --></classifier>
Run Code Online (Sandbox Code Playgroud)

如果此值与默认值不同,则需要在父 pom 和子 pom 中明确定义它。