Search code examples
mavenmaven-2

Should a pom declare direct dependencies if also included transitively?


My module MyLibrary depends on artifact ThirdPartyLibrary.

My module MyApplication depends on MyLibrary but also directly invokes the code in ThirdPartyLibrary.

Should MyApplication explicitly include ThirdPartyLibrary as a dependency in the pom, or rely on the fact that MyLibrary includes it as a dependency?


Solution

  • You should declare every dependency that your application depends on directly, even if (at the moment) another of your direct dependencies exposes the same dependency transitively to your application. Here’s why: If you upgrade MyApplication to use a future version of MyLibrary which (unbeknownst to you) no longer depends on ThirdPartyLibrary, your code will suddenly fail to compile – until you add an explicit dependency on ThirdPartyLibrary to MyApplication. This means that this dependency should have been there all along.

    FYI, the maven-dependency-plugin has a very helpful dependency:analyze goal which assists you in figuring out which dependencies your application should declare; it will look through the code of MyApplication, see the dependency on MyLibrary, and issue a warning that MyLibrary is used, but undeclared:

    [WARNING] Used undeclared dependencies found:
    [WARNING]    org.example:ThirdPartyLibrary:jar:1.0:compile