1. Overview
In this short tutorial, we’ll explore ways to clear our local Maven cache. We may want to do this in order to save disk space or clear up artifacts that we no longer reference.
We’ll first clear the cache manually, where we physically delete the directory. Then, we’ll clear our cache using the Maven Dependency Plugin, using some of the different plugin options available to us.
2. Deleting the Local Cache Directory
Our local Maven repositories are stored in different locations based on the operating system. Also, as the .m2 directory is likely to be hidden, we’ll need to change the directory properties in order to display it.
In Windows, the default location is:
C:\Users\<user_name>\.m2
And on the Mac:
/Users/<user_name>/.m2
And on Linux-based systems:
/home/<user_name>/.m2
Once we locate the directory, we can simply delete the folder .m2/repository. With Unix-based systems like MacOS or Linux, we can delete the directory with one command:
rm -rf ~/.m2/repository
If our cache directory isn’t in the default location, we can use the Maven Help Plugin to locate it:
mvn help:evaluate -Dexpression=settings.localRepository -q -DforceStdout
3. Using the Maven Dependency Plugin
Instead of deleting the cache directory directly, we can use the Maven Dependency Plugin with the purge-local-repository goal.
First, we need to navigate to the root of our Maven project. Then, we can run:
mvn dependency:purge-local-repository
When we run this plugin without any additional flags, it may download artifacts that aren’t present in our cache to resolve the dependency tree. This is known as transitive dependency resolution. Next, it deletes our local cache and, finally, re-downloads the artifacts.
Alternatively, in order to delete our cache and avoid the first step of pre-downloading the missing dependencies, we can pass in the flag actTransitively=false:
mvn dependency:purge-local-repository -DactTransitively=false
Finally, if we just want to clear out our cache, without pre-downloading or re-resolving the artifacts:
mvn dependency:purge-local-repository -DactTransitively=false -DreResolve=false
Here, we pass in an additional flag of reResolve=false, which tells the plugin to avoid re-downloading the dependencies.
4. Conclusion
In this short article, we looked at two ways to clear our local Maven cache.
First, we looked at manually emptying our local cache directory. Then, we used the Maven Dependency Plugin, exploring different options to achieve our desired outcome.