Search code examples
maven-2java

Building same project in Maven with different artifactid (based on JDK used)


I have a scenario where my project needs to be compiled in different JDKs and the resulting artifact name should be different based on the JDK used. For example, if the project name is MyProject and I call mvn install then it needs to be compiled in JDK 1.4 as well as JDK 1.5, and finally I get two jars of the same project: MyProjectJDK14-1.0 and MyProjectJDK15-1.0.

Is it possible to achieve this?


Solution

  • The Maven way to do this is not to change the finalName of the artifact but to use a classifier. For example:

    <project>
      ...
      <build>
        <plugins>
          <plugin>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
              <classifier>${envClassifier}</classifier>
            </configuration>
          </plugin>
        </plugins>
      </build>
      ...
      <profiles>
        <profile>
          <id>jdk16</id>
          <activation>
            <jdk>1.6</jdk>
          </activation>
          <properties>
            <envClassifier>jdk16</envClassifier>
          </properties>
        </profile>
        <profile>
          <id>jdk15</id>
          <activation>
            <jdk>1.5</jdk>
          </activation>
          <properties>
            <envClassifier>jdk15</envClassifier>
          </properties>
        </profile>
      </profiles>
    </project>
    

    The JAR artifact will be named ${finalName}-${envClassifier}.jar and included as a dependency using the following syntax:

    <dependency>
      <groupId>com.mycompany</groupId>
      <artifactId>my-project</artifactId>
      <version>1.0</version>
      <classifier>jdk16</classifier>
    </dependency>
    

    You'll have to call the Maven build twice to produce both jars (a decent CI engine can do that).