How to refer environment variable in POM.xml?
Reference an environment variable in pom.xml
with the ${env.VAR_NAME}
format. Here's how to leverage the JAVA_HOME
environment variable—just add ${env.JAVA_HOME}
.
Example:
The above snippet imports the JAVA_HOME
value into your Maven property.
Environment variables and build reproducibility
Build reproducibility is a primary aspect of any CI/CD process. It's important to remember, though, that environment variables, despite their versatility, can introduce unpredictability. Always document necessary environment variables, and it's a good practice to set default values:
Here, /default/path/to/jdk
acts as the fallback if JAVA_HOME
isn't set.
Profiles: managing project configurations like a Pro
In a heterogeneous environment, Maven profiles can serve as a useful tool to manage different configurations. Check the following code snippet in your pom.xml
file:
Invoking Maven with this profile is carried out from the command-line:
Trouble in paradise? Error-proofing your setup
Errors can pop up when you least expect them. Before your code goes into production, confirm the existence of environment variables required for your build process:
The build will be interrupted if JAVA_HOME
isn't set, safeguarding against surprises.
Plugin configurations and environment variables: A dynamic duo
Plugins can also be configured using environment variables. Take the maven-replacer-plugin
for instance:
Here, @envVar@
in the app.properties
file would be replaced with the value set in ENV_VARIABLE
. Clever, right?
Case sensitivity and compatibility checks: Cross your T's and dot your i's
Traditionally, environment variables are upper-case. Ensure you're using the same naming conventions:
Also verify your Maven version supports environment variable expansion to avoid unexpected outcomes.
Advanced substitution techniques
At times, you need more than simple substitution, you need creative alternatives. Consider scripting or use plugins for more complex substitutions:
The above does two things—maven_script.sh
sets up your environment variables, before seamlessly importing them into your Maven build without hardcoding them directly into pom.xml
.
Was this article helpful?