GitHub -hosted runners usually come with Maven pre-installed, but for version control and consistency, you should use the actions/setup-java action. This action configures the JDK and can automatically handle your Maven settings.
Optimizing how you handle Maven in GitHub Actions is the difference between a 2-minute build and a 10-minute wait. When developers search for they are usually looking for one of three things: installing Maven on a runner, downloading external dependencies, or sharing built artifacts (like JARs) between workflow jobs. 1. Setting Up the Maven Environment
- name: Cache Maven packages uses: actions/cache@v4 with: path: ~/.m2/repository key: $ runner.os -maven-$ hashFiles('**/pom.xml') restore-keys: | $ runner.os -maven- Use code with caution. 3. Downloading Built Maven Artifacts (JAR/WAR) github actions download maven
: If youcom/marketplace/actions/cache">actions/cache to key the cache against your pom.xml .
steps: - name: Checkout Code uses: actions/checkout@v4 - name: Set up JDK 17 uses: actions/setup-java@v4 with: java-version: '17' distribution: 'temurin' cache: 'maven' # Automatically caches downloaded dependencies Use code with caution. 2. Downloading Maven Dependencies (Caching) When developers search for they are usually looking
: As shown above, adding cache: 'maven' to setup-java is the easiest method.
If Job A builds a JAR and Job B needs to deploy it, you must "upload" it from the first job and "download" it in the second. GitHub Actions: Cache repo to speed up Maven builds downloading external dependencies
The most time-consuming part of a Java CI pipeline is Maven downloading the internet on every run. GitHub Actions allows you to cache the ~/.m2/repository directory to reuse these files across runs.