Today we will discuss working with pom.xml. Suppose you have a web application and you want to print its current version in some part of the page.
Of course, you can save the version in a separate parameter and read from there. But there is an option better. We can determine the version by reading it directly from pom.xml.
Coding
Create a new maven project. To work with the Maven model, we will use the maven-model library.
Add the maven-model dependencies
1 2 3 4 5 |
<dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-model</artifactId> <version>3.3.9</version> </dependency> |
Create an empty Main class. In the created class, add the code:
1 2 3 4 5 6 7 8 9 10 11 12 |
public class Main { public static void main(String[] args) throws IOException, XmlPullParserException { MavenXpp3Reader reader = new MavenXpp3Reader(); Model model = reader.read(new FileReader("pom.xml")); System.out.println(model.getId()); System.out.println(model.getGroupId()); System.out.println(model.getArtifactId()); System.out.println(model.getVersion()); } } |
Result
Here’s what we get as a result of running the program:
Need to retrieve pom version from CLI? Check this example
Thanks for the article ‘Retrieve app version from maven pom.xml in java’ . It helped me.