Get the information declared in the Apache Maven pom.xml file using the Maven Model library

In this tutorial, I will show you how to use Apache Maven’s Maven Model library to analyze and get information about dependencies and plugins being used for a Maven project.

First, I will create a new Maven project as an example:

Maven Model dependency is as follows:

The Maven project that I use to read the information is here https://github.com/khanhnguyenj/huongdanjava.com/tree/master/spring-boot-actuator!

The contents of the pom.xml file in this project are as follows:

To read the information in this pom.xml file, first, we will use Java’s FileReader object to connect and prepare to read the contents of the pom.xml file:

Once prepared, we will use the object of the MavenXpp3Reader class of the Maven Model library to read and parse the contents of this pom.xml file into the Model object of this library:

The Model object will contain the complete information of the pom.xml file, represented by Java objects. And so it allows us to get the information we want!

For example, if you now want to get the information of all the dependencies being declared, you can use the getDependencies() method of the Model object as follows:

As you can see, we will get the list of Dependency objects declared in the pom.xml file from this Model object.

Result:

Please note that if the pom.xml file uses the parent pom.xml file to manage the dependency version (like the example I’m using), to get the version information of a dependency, you need to read the content of the pom.xml file of this Parent object! Parent object information you can get as follows:

Result:

With the above example, I can also get the list of Plugins being declared as follows:

Result:

Add Comment