Skip to content
javahacks.dev
DevOps

How to Set Up CI for a Java Project With GitHub Actions

Build and test a Maven Java project on every push with GitHub Actions, using setup-java, a JDK matrix, test reports and a job that fails on broken tests.

6 min read
Summarize in AI
Flat illustration of settings switches, a slider and a gear, with the OpenJDK, GitHub Actions, Docker and Gradle logos.

A test suite that runs only on one developer's laptop protects nobody. Continuous integration is the habit of building and testing every change on a clean machine before it merges, so a broken commit is found in minutes by a robot and not on Friday by a customer. GitHub Actions is the lowest-friction way to get there for a repository already on GitHub: a YAML file in the repository, no server to run. This post builds the workflow for a Maven project from an empty file, adds Gradle, a JDK matrix, a database service for integration tests, test reports, and the branch protection that turns the build into a gate. The examples use JDK 25, Maven 3.9 and the current actions/setup-java.

The workflow

Workflows live in .github/workflows/. Create a file there named build.yml:

.github/workflows/build.ymlYAML
name: build

on:
  push:
    branches: [main]
  pull_request:

permissions:
  contents: read

concurrency:
  group: build-${{ github.ref }}
  cancel-in-progress: true

jobs:
  test:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v4

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

      - name: Build and test
        run: mvn -B -ntp verify

Each line earns its place. on runs the job on pushes to main and on every pull request. permissions: contents: read gives the job's token the least access it needs, which matters the day someone adds a step that should not be able to write. concurrency cancels a stale run when you push again to the same branch, saving minutes. timeout-minutes stops a hung test from burning a runner for six hours, which is the default limit. setup-java installs the JDK and, with cache: maven, restores ~/.m2 keyed on your pom.xml files. -B is batch mode, so the log has no progress bars, and -ntp hides download noise. The verify phase runs unit and integration tests and the checks bound to it; the phases are explained in the tutorial for the Maven POM and packaging.

Commit it and push. The run appears under the repository's Actions tab, and a passing build ends like this:

Text
[INFO] Tests run: 48, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

If the first run fails with a message about the release version, the build asked for a JDK the runner did not install, as explained in invalid target release. Make java-version match the maven.compiler.release in the POM.

Gradle

The same job for Gradle swaps the cache and the command. setup-gradle handles the Gradle user home cache and dependency graph submission:

.github/workflows/build.ymlYAML
      - uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: "25"

      - uses: gradle/actions/setup-gradle@v4

      - name: Build and test
        run: ./gradlew build --no-daemon

Use the wrapper (./gradlew) rather than a Gradle installed on the runner, so the CI version equals the one every developer uses. Make sure the wrapper file is executable in Git, or the step fails with Permission denied: git update-index --chmod=+x gradlew. A deeper look at what is cached and what is not, for both tools, is in caching Maven and Gradle in GitHub Actions.

Test several JDKs

A library, or an application that must run on more than one runtime, should build on each. A matrix runs the job once per value:

.github/workflows/build.ymlYAML
jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        java: ["21", "25"]
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: ${{ matrix.java }}
          cache: maven
      - run: mvn -B -ntp verify

fail-fast: false lets the other versions finish when one fails, so you see the whole picture in one run. Two jobs appear, test (21) and test (25). For an application you deploy on one JDK, a matrix only adds time; use it when the version spread is real. The release compiler flag and the runtime are separate things, so check that a build on 25 does not silently produce bytecode that breaks on 21 unless release is set.

Services for integration tests

Integration tests need a database. Actions can start a service container beside the job and wait for its health check:

.github/workflows/build.ymlYAML
jobs:
  test:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:17
        env:
          POSTGRES_USER: shop
          POSTGRES_PASSWORD: change-me
          POSTGRES_DB: shop
        ports:
          - 5432:5432
        options: >-
          --health-cmd "pg_isready -U shop"
          --health-interval 5s
          --health-timeout 3s
          --health-retries 10
    env:
      SPRING_DATASOURCE_URL: jdbc:postgresql://localhost:5432/shop
      SPRING_DATASOURCE_USERNAME: shop
      SPRING_DATASOURCE_PASSWORD: change-me
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: "25"
          cache: maven
      - run: mvn -B -ntp verify

The job runs on the host, so the database is on localhost. The health options make the step wait until PostgreSQL accepts connections. If your tests start their own containers with Testcontainers, you need no services block at all, because the runner has Docker available. Which approach to take per test layer is the subject of a practical testing strategy for Java.

Keep the test reports

When a test fails on the runner, the console log is the only evidence unless you saved the reports. Upload them even when the build fails:

YAML
      - name: Upload test reports
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: surefire-reports-${{ matrix.java || 'default' }}
          path: |
            target/surefire-reports
            target/failsafe-reports
          retention-days: 7

if: always() is the part people forget; without it the step is skipped exactly when you need it. A short retention keeps storage use down. For a readable summary on the pull request page, a test-report action can parse the JUnit XML and annotate the failing lines.

Make it a gate

A workflow that can be ignored is a suggestion. Turn it into a rule in the repository settings under Branches, by adding a branch protection rule or ruleset for main that requires the build check to pass and the branch to be up to date before merging. Also require a pull request, so nothing lands without a run. Two details trip people: the required check is matched by the job name, so renaming the job detaches the rule and the merge button turns green with nothing enforced; and a matrix job produces one check per entry, so require each one by name.

The failure you want is visible and early. A pull request with a red check shows the failing job, and the log shows the same Maven output you would see locally, which is why running mvn verify on a laptop first should rarely surprise you.

Secrets and forks

Never put credentials in the workflow file. Store them under the repository's secrets and reference them: ${{ secrets.REGISTRY_TOKEN }}. Pull requests from forks do not receive secrets, deliberately, so a build that needs one will fail for outside contributors; split the work into a job that needs no secrets, which runs on every pull request, and a separate job for publishing, which runs only on main after merge. Never run untrusted pull request code with write permissions or secrets, and avoid the pull_request_target trigger unless you know why you need it. Pin third-party actions to a release tag at least, and to a commit SHA for anything sensitive, since an action runs with your job's permissions. The syntax and the security model are in the GitHub Actions documentation, and the Java setup options are listed in the setup-java repository. Once the build is green, the next stage is publishing an image, covered in building and pushing Docker images in CI.

Where this does not apply

If your code is not on GitHub, the same steps map onto GitLab CI, Jenkins or another runner, with different syntax. A monorepo with many modules should build only what changed, using path filters or the build tool's affected-module support, or CI time grows with every module. And a very long test suite belongs split across parallel jobs, since a single 40 minute job defeats the point of fast feedback.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.