Oliver
Oliver

Reputation: 1645

Maven enforce no duplicate dependencies even of same version

We can use the maven-enforcer-plugin to prevent duplicate dependencies with difference versions.

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-enforcer-plugin</artifactId>
  <version>3.0.0</version>

  <executions>
    <execution>
      <id>no-duplicate-dependencies</id>

      <goals>
        <goal>enforce</goal>
      </goals>

      <configuration>
        <rules>
          <banDuplicatePomDependencyVersions/>
        </rules>
      </configuration>
    </execution>
  </executions>
</plugin>

What about for duplicate dependency declarations of the same version?

Consider that we are building a multi-module project. Say we start with project Foo.

Foo pom.xml

<dependencies>
  <dependency>
    <groupId>someGroup</groupId>
    <artifactId>someArtifact</artifactId>
    <version>1.0.0</version>
  </dependency>
</dependencies>

Later, we introduce the module Bar, which also depends on the same version someArtifact.

Bar pom.xml:

<dependencies>
  <dependency>
    <groupId>someGroup</groupId>
    <artifactId>someArtifact</artifactId>
    <version>1.0.0</version>
  </dependency>
</dependencies>

And Foo depends on Bar, so we update the POM.

Foo pom.xml

<dependencies>
  <dependency>
    <groupId>myGroup</groupId>
    <artifactId>bar</artifactId>
    <version>1.0.0</version>
  </dependency>

  <dependency>
    <groupId>someGroup</groupId>
    <artifactId>someArtifact</artifactId>
    <version>1.0.0</version>
  </dependency>
</dependencies>

As in the above example, and as our projects grow, we may forget that the same version of dependencies are already transitive dependencies.

In my mind, for organization sake, I find it messy to leave these duplicate declarations, such as it is with someArtifact.

I could write a new maven-enforcer-plugin rule, but maybe there is already a solution.

Upvotes: 0

Views: 535

Answers (1)

Bikram Pandey
Bikram Pandey

Reputation: 26

Try with dependencyConvergence rule. Add this to your parent pom.

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-enforcer-plugin</artifactId>
            <version>3.0.0-M3</version>
            <executions>
                <execution>
                    <id>enforce</id>
                    <configuration>
                        <rules>
                            <dependencyConvergence/>
                        </rules>
                    </configuration>
                    <goals>
                        <goal>enforce</goal>
                    </goals>
                </execution>
            </executions>
        </plugin> 

Reference :: https://maven.apache.org/enforcer/enforcer-rules/dependencyConvergence.html

Upvotes: 1

Related Questions