To compile the source code in Maven, we will usually use the Maven Compiler Plugin. It allows us to configure the version of Java that we want to compile the source code. For example, if you write code using the syntax of Java 7 and you want to compile source code also Java 7 then you can configure it as follows:
1 2 3 4 5 6 7 8 9 |
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.11.0</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> |
You can also compile source code from one Java version to another. For example, if you are writing code in accordance with the standard of Java 7 but you want your code compiled in accordance with Java 6 standards, you can use Maven Compiler Plugin as follows:
1 2 3 4 5 6 7 8 9 |
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.11.0</version> <configuration> <source>1.7</source> <target>1.6</target> </configuration> </plugin> |
If you used Java’s javac tool to compile the source code, then you will know the source and target tags in the configuration of this plugin correspond to the -source version and -target version options when you use javac to compile the source code.
You can also declare the following <properties> to configure the source and target of Java in the Maven project pom.xml file.
1 2 3 4 |
<properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> |
Then, you do not need to declare the source and target in the <configuration> section of Maven Compiler Plugin anymore.
Before Java 9, we used 1.x syntax with x as the Java version to declare the Java version in the Maven Compiler Plugin. From Java 9 onwards, you don’t need to do that anymore, just declare the exact Java version you want to use.
Now you can declare as follows:
1 2 3 4 5 6 7 8 9 |
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.11.0</version> <configuration> <source>12</source> <target>12</target> </configuration> </plugin> |
The <properties> section can be declared as follows:
1 2 3 4 |
<properties> <maven.compiler.source>12</maven.compiler.source> <maven.compiler.target>12</maven.compiler.target> </properties> |
From Java 9 onwards, the javac tool also supports one more option, -release version to specify the Java version that you want to build a Java project. For Maven, you can declare as follows:
1 2 3 |
<properties> <maven.compiler.release>17</maven.compiler.release> </properties> |