naaz naaz - 20 days ago 5
Java Question

The Uniqueness of an artifactId in maven


  • Let's say that there are 2 maven artifacts (local) with the same
    groupId but with a different artifactId.

  • The different artifactId should make each maven artifact unique.

  • However, if both of the unique artifacts each have a class with that share the same name. that class will not be unique because when it is imported to java it will use the groupId.className format. and the neither groupId nor the className are unique (in the discussed case).

  • This will result in an issue of ambiguity as to determining which class to use.

  • Upon testing it seems that the dependency declared first in the pom.xml file will be used.



The Question Are


  1. What is the best practice solve/avoid this issue?

  2. Why does maven's artifactId coordinate contribute to the uniqueness of a maven artifact within the repository but not inside the java code?



Example Code:
Maven - Same Class Name Same GroupId Different ArtifactId



  • Project1 is the first artifact.

  • Project2 is the second artifact.

  • "Projects User" is the artifact/project that will depend on both Project1 & Project2.

  • Project1 & Project2 both have a class named
    Utilities
    .

  • The class
    Utilities
    have a static method
    public static String getDescription()
    that returns a
    string
    containing the current project's artifact coordinates as well as the project name.

  • Utilities.getDescription()
    resulting
    String
    is called to see if an error will occur somewhere, and to see how it will be resolved.

  • The output depends on which dependency was declared first in the pom.xml file of the "Projects User" artifact.



Edited : Follow up Question


  • Is there an archetype that will create the java package using both the artifactId and groupId instead of having to do it manually every
    time?


Answer

What is the best practice solve/avoid this issue?

We include the groupId and artifactId as the base package in the module. This way it is not possible to have the same class in two modules as the packages would be different.

e.g.

<groupId>net.openhft</groupId>
<artifactId>chronicle-bytes</artifactId>

has everything under the package

package net.openhft.chronicle.bytes;

Also if you know the package of a class you know which JAR it must be in.

if you have a class two JARs need, I suggest creating a common module, they both depend on.

Note: it is general practice to use your company domain name (and notional division as well) as the base of your package. Maven recommend using your domain name as you groupId and if you release to Maven Central this is now a requirement. The above strategy supports both recommendations.

Why does maven's artifactId coordinate contribute to the uniqueness of a maven artifact within the repository but not inside the java code?

Maven doesn't take any notice of the contents of the JAR.