Use installed java version in maven repository

Viewed 129

It is a simple question, but I didn't find any good solution.

I have created a maven project that is compatible to java8+. I want that, whenever someone builds the project, maven should use the java installed java version.

In other words, I want soneting like:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.7.0</version>
    <configuration>
        <source>${java.version}</source>
        <target>${java.version}</target>
        <compilerVersion>${java.version}</compilerVersion>
    </configuration>
</plugin>

For JAXB I used the following:

<profile>
    <id>java-9+</id>
    <activation>
        <activeByDefault>true</activeByDefault>
    </activation>
    <dependencies>
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.0</version>
        </dependency>
    </dependencies>
</profile>
<profile>
    <id>java-8</id>
    <activation>
        <jdk>1.8</jdk>
    </activation>
    <dependencies>
        <!-- add Java 8 dependencies -->
    </dependencies>
</profile>

It needs to work in cli(mvn commands), eclipse and in IntelliJ.

2 Answers

While you CAN manage dependencies through profiles activation

<profile>
    <activation>
        <jdk>[9,)</jdk>
    </activation>

... for users of your library it would be unclear - either your library was build with or without jaxb-api.

More clear way would be to build 2 separate modules. For Java 8:

<artifactId>yourModule</artifactId>
<dependencies>
    <!-- Java 8 dependencies -->
</dependencies>

And for Java 9+:

<artifactId>yourModule-9</artifactId>
<dependencies>
    <dependency>
        <groupId>${project.groupId}</groupId>
        <artifactId>yourModule</artifactId>
        <version>${project.version}</version>
        <excludes>
            <!-- Explicitly exclude all irrelevant dependencies. -->
        </excludes>
    </dependency>
    <dependency>
        <groupId>javax.xml.bind</groupId>
        <artifactId>jaxb-api</artifactId>
        <version>2.3.0</version>
    </dependency>
</dependencies>

This way your users will have clear and predictable dependencies.

You can activate a profile based on the JDK:

<profiles>
  <profile>
    <activation>
      <jdk>1.7</jdk>
    </activation>
    ...
  </profile>
</profiles>
Related