Maven dependencies done right

Maven is a great tool for managing dependencies. The default configuration lacks some verifications and basic checks, that can easily be enforced with extra tools.

Define versions inside dependencyManagement

Maven supports defining project dependency versions on two places: inside project / dependencyManagement / dependencies and project / dependencies.

Don’t: define versions inside project / dependencies.

Do: define versions inside project / dependencyManagement / dependencies.

Every developer working with dependencies must understand this. Read Maven Dependencies documentation.

Prevent duplicate classes

Some classes are available in multiple dependencies. This causes classes to be loaded multiple times in the classpath.

The result is like Russian Roulette: the version of the class loaded, is randomly chosen by the JVM.

Some causes of how classes get duplicated:

  • Dependencies get relocated, for example library javassist used to be in javassist:javassist, but was moved to org.javassists:javassist.
  • Dependencies get merged. For example, Google Collections, was merged into Google Guava
  • Dependencies pack external classes inside their own jar (instead of letting their dependencies be managed by Maven).
  • Some packages manage to put class-files multiple times in a jra (like XMLBeans).

Do:

  • Detect duplicate classes using theBan Duplicate Classes rule ofMaven Enforcer plugin.
  • Fail the build when duplicates are found.
  • Configure exceptions for duplicate classes you cannot get rid of.
  • Exclude libraries from the build that cause duplicates (it takes care and craftsmanship to chose the right ones to exclude).

Require upper-bound dependencies

Sometimes one dependency is used multiple times by transitive dependencies. Often happens with common libraries like Guava, Apache Commons Lang, Apache Commons IO etc.

Maven does not chose the correct version automatically. Maven selects the version of ‘shortest path to dependency’. In general, what is needed, is the highest version.

Do:

  • Detect duplicate classes using the Require Upper Bound Dependencies Enforcer plugin rule.
  • Set the version in dependencyManagement in the project root pom.xml file.

Keeping dependencies up-to-date

Keep your versions up-to-date using Versions Maven Plugin. This plugin can reduce effort of team in keeping dependencies up to date.

Use OWASP depedency-check for vulnerabilities

Common Vulnerabilities and Exposures (CVE) of software components are collected by NIST.

There is a OWASP Maven dependency-check plugin to check for CVEs in Java and Javascript code packaged inside.

DO:

  • Configure the plugin.
  • Create a nightly build on the CI server that runs the plugin.

Contact

Have some remarks, or need help fixing your Software build process? Get in touch by sending an email to info@squins.com