GitHub Actions for Java (Maven & Gradle)
Build a CI workflow with caching, tests, reports and optional matrix, schedule, Sonar and Docker, using current actions.
A continuous integration workflow for Java
A good CI pipeline for a Java project does a few things on every push and pull request: check out the code, install the right JDK, restore cached dependencies, build, run the tests, keep the reports and the jar. Writing that in YAML from memory means looking up action versions and cache settings each time. This builder produces a clean workflow for Maven or Gradle with the options teams usually want.
Pick the build tool, the JDK version and distribution, the branches to build and whether to run pull requests, a nightly schedule, a Java version matrix, SonarCloud analysis and a Docker image push to GitHub Container Registry. The generated workflow uses current official actions (checkout@v4, setup-java@v4, setup-gradle@v4, upload-artifact@v4), least-privilege permissions and concurrency control.
Choices explained
- Matrix builds the same job on several Java versions in parallel, useful for libraries;
fail-fastis off so one failing version does not hide the others. - Schedule runs the workflow on a cron in UTC on the default branch. The cron expression is validated with the GitHub Actions rules used by the cron builder on this site, and busy minutes (0 and 30) are flagged because GitHub delays or drops runs at peak times.
- Docker builds and pushes an image tagged with the commit SHA, only for pushes to the main branch, using the built-in token.
- Test reports are uploaded even when tests fail, so you can read them.
For production repositories pin third-party actions to a full commit SHA. Adjust the commands for multi-module projects. The file is generated in your browser.
Frequently asked questions
Where does the workflow file go?
Save it as .github/workflows/ci.yml in your repository. GitHub runs every workflow file in that folder automatically for the events listed under on:.
Why use setup-java with a cache?
The setup-java action installs the JDK and, with cache: maven or cache: gradle, stores the dependency directory between runs, keyed on your pom or build files. Builds that download nothing are much faster.
What does the concurrency block do?
It cancels an older run of the same workflow and branch when you push again, so you do not pay for builds of commits that are already outdated.
Which JDK distribution should I choose?
Temurin (Eclipse Adoptium) is the common default. Corretto, Zulu, Liberica and Microsoft builds are also available. Use the one that matches what you run in production.