Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 41 ยท Projects

Project: A CI Pipeline for a Maven Project

Set up GitHub Actions for a Maven project: build and test on every push, cache dependencies, report coverage, and release on a version tag.

A build that only works on your laptop is not a build, it is a ritual. Continuous integration (CI) runs the same Maven commands on a clean machine for every change, so a broken test or a forgotten file is caught within minutes and not after a release. In this project you will write a GitHub Actions workflow that builds and tests on every push and pull request, caches dependencies, publishes a coverage report and creates a release when you push a version tag.

The earlier lesson Maven in CI and Faster Builds covers the tuning options. This one is a complete, working example. The YAML below is read-only here, because Actions runs on GitHub's servers. The TryIts are stand-ins: a model of the dependency cache and its keys, and a runner that decides which jobs run for which event.

The pipeline in four jobs

Build and test Every push and pull request.
Coverage JaCoCo report attached to the run.
Dependency review Pull requests only.
Release Only on a v* tag, after green tests.
1 / 2

Prepare the project

CI should run the exact command a developer runs locally. Keep it to one line: mvn -B -ntp verify. Two flags matter in CI. -B (batch mode) disables colors and interactive prompts, and -ntp (no transfer progress) removes thousands of "Downloading..." lines from the log. For reproducibility use the Maven Wrapper so the pipeline uses the same Maven version as everyone else: ./mvnw -B -ntp verify. The examples below call mvn for brevity, which on GitHub's runners is a preinstalled recent Maven 3.9.

For coverage, add JaCoCo to the POM. The agent records which lines ran during tests, and the report goal writes HTML to target/site/jacoco. The check goal fails the build when coverage drops below a threshold (see Code Quality).

XML
<plugin>
  <groupId>org.jacoco</groupId>
  <artifactId>jacoco-maven-plugin</artifactId>
  <version>0.8.12</version>
  <executions>
    <execution>
      <goals><goal>prepare-agent</goal></goals>
    </execution>
    <execution>
      <id>report</id>
      <phase>verify</phase>
      <goals><goal>report</goal></goals>
    </execution>
    <execution>
      <id>check</id>
      <phase>verify</phase>
      <goals><goal>check</goal></goals>
      <configuration>
        <rules>
          <rule>
            <element>BUNDLE</element>
            <limits>
              <limit>
                <counter>LINE</counter>
                <value>COVEREDRATIO</value>
                <minimum>0.80</minimum>
              </limit>
            </limits>
          </rule>
        </rules>
      </configuration>
    </execution>
  </executions>
</plugin>

The workflow file

Save the next file as .github/workflows/build.yml. Read it top to bottom: the triggers, the shared settings, then three jobs.

YAML
name: build

on:
  push:
    branches: [main]
    tags: ["v*"]
  pull_request:
    branches: [main]

permissions:
  contents: read

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: ${{ github.event_name == 'pull_request' }}

jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        java: [21, 25]
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: ${{ matrix.java }}
          cache: maven

      - name: Build, test and check coverage
        run: mvn -B -ntp verify

      - name: Upload coverage report
        if: matrix.java == 21
        uses: actions/upload-artifact@v4
        with:
          name: jacoco-report
          path: target/site/jacoco

  dependency-review:
    if: github.event_name == 'pull_request'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/dependency-review-action@v4

  release:
    needs: build
    if: startsWith(github.ref, 'refs/tags/v')
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: 21
          cache: maven

      - name: Tag must match the POM version
        run: |
          pom_version=$(mvn -q -B -ntp help:evaluate -Dexpression=project.version -DforceStdout)
          if [ "v$pom_version" != "$GITHUB_REF_NAME" ]; then
            echo "Tag $GITHUB_REF_NAME does not match POM version $pom_version"
            exit 1
          fi

      - name: Package
        run: mvn -B -ntp -DskipTests package

      - name: Create GitHub release
        env:
          GH_TOKEN: ${{ github.token }}
        run: gh release create "$GITHUB_REF_NAME" target/*.jar --generate-notes

What each part does

  • Triggers. push to main, to any tag beginning with v, and pull_request against main. A feature branch gets built when its pull request opens.
  • permissions: contents: read. The workflow's token can only read by default. Only the release job asks for contents: write, which limits the damage if a step is compromised.
  • concurrency. A new push to the same pull request cancels the older run. Runs for main and tags are never cancelled, because the expression is true only for pull requests.
  • Matrix. The same job runs on Java 21 and 25. Testing the newest JDK early shows you problems like old plugins that cannot read new class files (see Troubleshooting Common Maven Errors).
  • cache: maven. The setup-java action restores ~/.m2/repository before the build and saves it afterward, keyed on a hash of every pom.xml.
  • Release job. It needs the build job to succeed, runs only for tags that start with v, checks that the tag equals the POM version, packages once and creates the release with the jar attached. Publishing to Maven Central is a further step described in Publishing; it needs signing keys stored as repository secrets, never in the workflow file.

How the cache behaves

The cache key contains a hash of the POM files. While the POMs are unchanged, each run restores the same cache and downloads nothing. When you add a dependency, the hash changes, the exact key misses, and the action falls back to the newest cache with the same prefix, so only the new artifacts are downloaded. Then it saves a new cache under the new key.

The first TryIt models this logic. It uses a real SHA-256 over the POM contents, like hashFiles, but the key format and cache store are simplified stand-ins for what setup-java does internally.

Java Cache keys and restore keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice what the stand-in leaves out: real caches are immutable per key, are scoped per branch, expire after a week without use, and have a size limit. Those rules are GitHub's, not Maven's.

Which jobs run when

A pipeline is a small decision table: for each event, which jobs run, which are skipped and which fail. The if: conditions and the needs: relationship are the whole logic. The second TryIt evaluates that table for five scenarios, including a release attempted with a tag that does not match the POM and a release attempted with failing tests.

Java Which jobs run for which event?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The runner is a stand-in for GitHub's scheduler; real Actions also run matrix legs in parallel, track timeouts and expose expressions far richer than startsWith. The point is that you can reason about a pipeline as data: triggers choose the events, conditions choose the jobs, needs orders them.

Keeping the pipeline healthy

  • Pin action versions. @v4 follows a moving tag; for stricter supply-chain control, pin to a full commit SHA and let Dependabot update it.
  • Keep secrets out of logs and forks. Pull requests from forks do not receive repository secrets, which is why signing and deploying live in the tag-triggered release job.
  • Fail fast, then dig. When a CI run fails, read the first ERROR line, as in the troubleshooting lesson, and re-run the same command locally.
  • Treat flaky tests as bugs. A test that fails one run in twenty teaches everyone to ignore red builds.
  • Mind the cost. The matrix doubles minutes. Run the extra JDK only on main if the budget is tight.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which flag removes the long 'Downloading from central' lines from a CI log?

    --no-transfer-progress (-ntp) hides download progress. -B (batch mode) additionally disables colors and prompts.
  2. 2. A tag v1.3.0 is pushed, but the POM says 1.3.1-SNAPSHOT. What should the release job do?

    A release whose tag and POM version disagree publishes confusing artifacts. A guard step that compares them stops it early.
  3. 3. Why does the release job declare needs: build?

    needs makes the job wait for the named job and skips it if that job did not succeed.
  4. 4. After a new dependency is added to the POM, what happens to the Maven cache in the next run?

    The key contains a hash of the POM files, so a changed POM gives a new key. The restore-key prefix finds the previous cache, so only the new artifacts need downloading.

Summary

  • CI runs one command, mvn -B -ntp verify, on a clean machine for every push and pull request.
  • setup-java with cache: maven caches ~/.m2, keyed by a hash of the POM files, with a prefix fallback.
  • JaCoCo's report and check goals give a coverage report and a failing threshold.
  • A release job triggered by v* tags, with needs: build and a tag-equals-POM check, keeps releases safe.
  • The workflow YAML was not executed here; the TryIts are stand-ins for the cache and the job scheduler.

Finally, test yourself on the whole track: Practice Exercises with Solutions.