Retrieve version from maven pom.xml in code
Use Maven resource filtering for injecting the Maven project's version at runtime in your code.
- Apply filtering to
pom.xml
:
- Create
version.properties
insrc/main/resources
:
version=${project.version}
Maven swaps ${project.version}
for the current version during the build.
- Load the property in Java:
Voila! You have the Maven project's version in your Java code.
A pinch of Maven profiles to spice things up
Boost the Maven build's flexibility with Maven profiles. Tailor your properties file to the active profile by defining different version identifiers or other environment-specific parameters.
Remember to set your resource filtering to ${env.version}
to make this magic work.
Ensuring version retrieval during tests
Running unit tests might prompt the infamous "properties file missing." To tackle this, ensure your test setup mirrors the primary build's resource handling in your pom.xml
.
Consider tweaking the maven-jar-plugin to embed version info for MANIFEST.MF
.
This way, if the properties method fails, App.class.getPackage().getImplementationVersion()
comes to rescue, like your favorite superhero.
The art of reading pom.xml programmatically
Project situations may not always favor reading from the properties file. You can navigate your pom.xml
programmatically using Apache Maven libraries_.
Remember to include maven-model in your project dependency before "pom-ing" around.
From carve-stone to Swiss Army Knife approach with Maven
Though Maven primarily aids the build process, it could turn into a Swiss-Army knife, making runtime behaviors more adjustable. For instance, besides version info, pom.properties
could also be honed for groupId and artifactId.
During the Maven package phase, these values generate automatically, proving to be handy at runtime.
Effective Version Retrieval: Building the Perfect Execution
The getImplementationVersion()
method is efficient for getting your project's version, but incorporating best practices adds robustness and reliability.
- Make the best use of maven-jar-plugin and fine-tune your JAR's
MANIFEST.MF
to snapshot version info. - Robust testing ensures the version retrieval works in all environments, strengthening the integration with CI/CD pipelines.
- Respect Maven's non-goal philosophy: Using Maven for reading
pom.xml
during runtime is not recommended. Indirect data access via properties and manifest files is preferred.
When you consider all these, you're preparing a recipe not just for version retrieval but for a resilient and adaptable system with clear benefits.
Was this article helpful?