This article is part of the Maven source Code Parsing series: How does dependency mediation work? The fifth chapter mainly introduces the principle that the latter covers the former declaration in the same document.

Please read the rest of the series, in order, at juejin.cn/post/703292…

scenario

This time we make A directly dependent on X and declare X twice in A’s POM.xml, version 1.0 and version 2.0. As follows:


      
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>mavenDependencyDemo</artifactId>
        <groupId>org.example</groupId>
        <version>1.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>A</artifactId>
    <version>1.0</version>

    <dependencies>

        <dependency>
            <groupId>org.example</groupId>
            <artifactId>X</artifactId>
            <version>1.0</version>
        </dependency>

        <dependency>
            <groupId>org.example</groupId>
            <artifactId>X</artifactId>
            <version>2.0</version>
        </dependency>


    </dependencies>

</project>

 
Copy the code

The source code

This scenario is relatively simple and does not involve mediators. Let’s look at the main flow directly from the diagram:

summary

If two groupId and artifactId dependencies are declared in the same POM file, the last dependency declared will take precedence. Because, at the implementation level, they are stored in the Map, the latter dependency overwrites the former. This lends credence to the principle’s name: the latter overwrites the former in the same file.

In fact, the console has already printed a warning, and if you look closely you can see that:

The corresponding source code is here: