Cup of Java

Tales of a lost software developer

Fight Dependency Hell in Maven

Did you ever use Maven in one of your projects? First you probably were amazed by the way you can declare dependencies and use all the nice plugins. Then you may realized that the handling of transitive dependencies is solved… well, let me say it could be better. But there is another Maven plugin that helps you to clean your dependencies and also to ensure that transitive dependencies will never cause to rot your dependency definitions again.

As mentioned in this blog posting, the Enforcer Maven Plugin helps. It offers a dependency convergence rule that checks the following:

If a project has two dependencies, A and B, both depending on the same artifact, C, this rule will fail the build if A depends on a different version of C then the version of C depended on by B.

That is exactly what I want in all of my projects managed by Maven! Therefore, I add the enforcer plugin to the pom file and enable the DependencyConvergence rule. I find it useful when the enforcer plugin is executed during the validate phase. This causes the build to break before compiling if the dependencies do not converge. Then you have to exclude the unwanted transitive dependencies or change the versions. Very handy!

Enable dependency convergence check in your Maven build
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-enforcer-plugin</artifactId>
  <version>1.0.1</version>
  <configuration>
    <rules>
      <DependencyConvergence/>
    </rules>
  </configuration>
  <executions>
    <execution>
      <id>enforce</id>
      <goals>
        <goal>enforce</goal>
      </goals>
      <phase>validate</phase>
    </execution>
  </executions>
</plugin>

Just try this in one of your projects. You will be quite surprised what for a mess your actual dependency definitions are.

Comments