Quick find unused maven dependencies
This is a common practice that when we use a maven project, we find it hard to analyze what all dependencies and transitive dependencies comes bundled when we add a library. The general approach taken by most of the developers is manually inspecting if “I had used this dependency or not and if not then how can I remove it.”
The easiest way to see what all dependencies project uses is using the simple maven command in the root directory of project :
mvn dependency : tree
But this gives the entire hierarchy of the dependencies in project and not specify which library is used actually used in project and which not. See Below output :
So in this tutorial we will address how to use the Maven dependency plugin, a plugin that helps us find unused dependencies in our project.
Pom Dependencies
In the below pom extract, I have added couple of dependencies from which I am going to focus on apache commons-lang3, as I have specified that dependency in project and not going to use anywhere in project.
You may observe the plugin reports same for spring boot starter and web boiler plate dependencies, as some of them are used and some are unused, but we can ignore them for now and follow for apache commons-lang3 dependency only.
Now define the Maven dependency plugin in our pom.
Code Usages
The below is the only piece of code written and I have not used anywhere the apache commons-lang3 dependency.
Now run the below command
mvn dependency:analyze
The output shows all used and unused dependencies in the project.
Define Dependencies as Used
Now depending on the project, sometimes it may be needed to load classes at runtime, and the dependencies are not used at compile-time, the maven-dependency-plugin would issue a warning stating that a dependency is not being used, while in fact it is.
For that, we can specify and force the plugin that a library is being used. We can do this by listing the dependencies inside the usedDependencies property:
Run again the mvn dependency command
mvn dependency:analyze
We see that the commons-lang3 dependency is no longer considered in the output report.
Summary
We have just seen, how to find used/unused maven dependencies in a Spring boot maven project. It’s always a good practice to check for used/unused dependencies regularly since it improves maintainability of the code and reduces the lib size of our project. Go through the official documentation of Maven dependency plugin for extended use of the plugin.
Source code with samples can be found here. Happy Learning !!