Setting The Java Maven Version

In this tutorial we will look at how to set the Java version in maven.

By default maven reads the version from the JAVA_HOME environment variable.

We can check the maven Java version by running the following command on the command line assuming maven is configured correctly:

1
mvn -v

The above command will output the Java version used by Maven.

Maven Compiler Plugin

We can use the Maven compiler plugin to configure the Java version. First we need to set the complier plugin Java version as Maven properties.

1
2
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>

The Maven compiler can use the -target and -source versions. For example if we want to use the Maven compiler with Java 8 we should set the source to 1.8.

Moreover, for the compiled classes to be compatible with Java 1.8, we must set the target value to 1.8.

The Maven compiler accepts this command with –target and –source versions. If we want to use the Java 8 language features the –source should be set to 1.8. To configure the Maven complier plugin we add it to the build section of our Maven pom.xml file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>${maven.compiler.source}</source>
               <target>${maven.compiler.target}</target>
            </configuration>
        </plugin>
    </plugins>
</build>

The above will configure the Maven compiler to use Java version 1.8.

Maven From Java 9

From JDK version 9 the new -release command-line option can be used. The release option will produce Java class files compatible with the Java platform version.

To compile and run the the Java code on older versions of the platform we must also specify the -bootclasspath option.

The new -release option replaces the flags: -source, -target, and -bootclasspath.

We can define the release in our Maven pom.xml by setting the property:

1
<maven.compiler.release>9</maven.compiler.release>

We can also configure the Maven compiler plugin from version 3.6 to use this property:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.6.2</version>
            <configuration>
                <release>${maven.compiler.release}</release>
            </configuration>
        </plugin>
    </plugins>
</build>

In the above snippets we configure the release version to compile our code for Java 9.

Conclusion

In this short tutorial we looked at home to set the Java version in Maven. We also looked at some of the changes to set the Java version in Maven from Java 9 and beyond.