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:
And on the Mac:
And on Linux-based systems:
Once we locate the directory, we can simply delete it. With Unix-based systems like MacOS or Linux, we can delete the directory with one command:
rm -rf ~/.m2
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:
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.
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.