How to set a specific Java version in Maven?
To inform Maven which Java version to use, set the maven.compiler.source
and maven.compiler.target
in your pom.xml
:
Simply replace 11
with your desired Java version. This ensures that Maven compiles your code using Java 11, provided it is installed.
Setting Java version via JAVA_HOME
Maven uses the JAVA_HOME
environment variable to determine which Java version to employ. By setting this variable, you control which JDK Maven picks up. Here's how you do it:
Don't forget to revert JAVA_HOME
once done or James Gosling might come to your dreams ~ holding a cup of Java.
Customizing the Maven script
You can directly edit the mvn
, mvn.bat
, or mvn.cmd
scripts, specifically setting the JAVA_HOME
right there. It's like ordering a coffee directly from the counter, skipping the queue.
Using the magic toolchains.xml
Maven has a toolchains.xml
configuration mechanism, handy for specifying different JDKs for individual projects. This is an especially useful feature from Maven 2.0.9 onwards. Maven docs have got you covered on the setup.
Create aliases for quick switching
On Unix systems, you can configure aliases in your .bashrc
or .zshrc
file to quickly switch Java versions:
This command creates an alias mvn11
that runs Maven with Java 11. It's like having a fast travel point at your favorite tavern in an RPG!
Use modern Maven features
The <release>
property in the compiler plugin, available from Java 9, is another way to tell Maven about the Java version:
No more time travel: Maven ensures you're using features available in that specific Java release.
Specific Scenarios: Maven & Java versions
Building with the previous JDK
Let's assume your project still uses Java 1.7 in a Java 1.8 landscape. You configure JDK 1.7 by setting:
Verify the Java version used by Maven
To check which Java version Maven is using, fire this command:
Look out for the Java version in the output. Hope it matches your expectations, unlike the final season of your favorite show.
Using .mavenrc for individual preferences
To set JAVA_HOME
for a single user and not meddle with the system-wide settings, create a ~/.mavenrc
file. It's like having your own personalized settings for the TV remote.
Consistent builds with Maven Wrapper
For consistent build environments across developers and CI servers, commit a Maven wrapper (mvnw
) into your source control. Now everybody is synchronised, just like a perfectly executed group dance routine.
Was this article helpful?