How to Cache Maven .m2 in GitHub Actions
Maven downloads its entire dependency tree from scratch on a fresh runner unless the local repo is cached.
Use actions/setup-java with built-in Maven caching, or cache ~/.m2/repository directly keyed on pom.xml.
Steps
- Add
actions/setup-javaand setcache: mavenfor the simplest path. - Or add an explicit
actions/cachestep over~/.m2/repository. - Key on
hashFiles(**/pom.xml)with arestore-keysfallback. - Run
mvn -B verifyso the cache populates on first use.
Workflow
.github/workflows/maven.yml
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
cache: maven
- run: mvn -B verifyGotchas
- Avoid caching
-SNAPSHOTartifacts you publish locally; they go stale and mask real failures. - Use
-B(batch mode) to keep logs clean and downloads deterministic. - Latchkey keeps the Maven repository warm between runs so builds are cheaper and self-healing.
Related guides
How to Cache the .gradle Directory in GitHub ActionsCache the Gradle user home and wrapper in GitHub Actions so Java and Kotlin builds reuse downloaded dependenc…
How to Cache pip Wheels in GitHub ActionsCache the pip wheel cache in GitHub Actions, keyed on requirements files, so Python CI skips rebuilding and r…