What is the @nx/gradle plugin and how does it work with Spring Boot?
The split is deliberate. Gradle remains the build tool: it compiles Java, resolves Maven dependencies, runs JUnit, and produces the executable jar through the Spring Boot Gradle plugin. @nx/gradle does none of that work. It asks Gradle for its project model, meaning which subprojects exist, which tasks they expose, and which project dependencies connect them. It then registers a matching Nx project for each Gradle project, with targets that delegate back to the Gradle wrapper. You don't write a project.json per service, because the Gradle build files are the only source of truth.
This matters in a polyglot Nx workspace. Nx can then place a Spring Boot service and the TypeScript frontend that calls it in one graph, and its scheduling, caching and affected detection cover both. Gradle keeps doing the job it is good at.
settings.gradle.kts Nx project graph
include("services:orders") orders ── build, test, bootJar
include("services:billing") │
include("libs:domain") ▼
gradlew (Gradle root) domain ── build, test
│ ▲
▼ │
@nx/gradle reads Gradle's model ──► billing ── build, test
web-app (TypeScript) ── build, test
The plugin has changed its inference mechanism, target naming and options across Nx releases. Read the documentation for the version you have installed, not whatever a search returns. Pin Nx and the Gradle wrapper version together, and upgrade them as a pair.
+-- Gradle root (Gradle is the build tool) --------------------------------+
| settings.gradle.kts gradlew + gradle/wrapper (pinned) |
| include("services:orders") compiles Java, resolves deps, |
| include("services:billing") runs JUnit, builds Spring Boot jar |
| include("libs:domain") |
+--------------------------------------------------------------------------+
| project model: subprojects, tasks, deps
v
+--------------------------------+
| @nx/gradle plugin |
| registers Nx projects/targets |
| no hand-written project.json |
+--------------------------------+
|
v
+-- Nx project graph ------------------------------------------------------+
| +----------------+ +----------------+ |
| | orders | | billing | |
| | build, test | | build, test | |
| +-------+--------+ +-------+--------+ |
| | | |
| +-------------------+-------------------+ |
| v |
| +-------+--------+ +----------------------+ |
| | domain | | web-app (TypeScript) | |
| | build, test | | build, test | |
| +----------------+ +----------------------+ |
| Gradle edges inferred from model; targets run ./gradlew <task> |
+--------------------------------------------------------------------------+
Gradle keeps compiling, resolving dependencies and packaging the Spring Boot jar, while @nx/gradle reads Gradle's project model and registers matching Nx projects, targets and dependency edges next to the workspace's TypeScript projects.
Who should put Spring Boot services in a polyglot Nx workspace, and when should you avoid it?
The case for this setup rests on one idea: a change should be evaluated once, across every language it touches. If a Spring Boot service publishes an OpenAPI spec and a TypeScript client is generated from it, a single pull request can change the controller, the generated client and the Angular or React screen that calls it. Nx can trace that chain only if the Java projects are in its project graph. With the services in the graph, nx affected selects the right tests on both sides, cached results replay in the same way for Gradle and TypeScript tasks, and engineers learn one entry point instead of two.
Platform teams running mixed-language repositories gain the most, especially when backend and frontend releases are coupled and contract drift has already caused production bugs.
When to keep Java out of the workspace
- The JVM services share little with the rest of the repo. If nothing in TypeScript depends on them, Nx adds a layer without finding any affected relationships that Gradle couldn't find on its own.
- The Gradle build is large or slow to configure. Nx must query Gradle to build the project graph. If configuration takes a long time, every command that needs the graph waits for it.
- The team won't agree on canonical commands. If half the engineers run
./gradlewfrom IntelliJ and the other half run Nx, caching and affected detection give inconsistent results.
The costs are real. You add tooling complexity, CI runners that need both a JDK and Node.js, and a split developer experience. Weigh them against the CI time you save by testing only affected projects and replaying cached results, and estimate that saving from your own pipeline history.
Laying out the repository and adding @nx/gradle
Start with Gradle, not Nx. The plugin reads your Gradle build, so the build should already work on its own before Nx sees it.
Define the Gradle build
Put settings.gradle.kts at the repository root and include each subproject by path, for example include(":apps:orders-service", ":libs:shared"). A single root build means one project graph. Gradle resolves cross-project dependencies itself, and the Nx plugin has one place to read from.
In apps/orders-service/build.gradle.kts, apply the org.springframework.boot and io.spring.dependency-management plugins alongside java. The dependency-management plugin imports Spring Boot's managed versions, so starters can be declared without version numbers. Then add implementation(project(":libs:shared")). This declaration matters beyond compilation. It is the edge Nx later turns into a project dependency, so changes to the library mark the service as affected.
Give libs/shared/build.gradle.kts the java-library plugin and not Spring Boot. java-library separates api from implementation dependencies. A library should also produce a plain jar, not a repackaged executable one.
Commit the wrapper
Generate and commit gradlew, gradlew.bat and the gradle/wrapper/ directory at the Gradle root. Nx invokes the wrapper. Committing it means developers, Nx and CI all run the same Gradle version rather than whatever happens to be installed.
Add the plugin
From the workspace root, run nx add @nx/gradle. This installs the package and registers it in nx.json. Review the generated plugin entry and its target-name options against the documentation for your installed version, because the available options have changed between releases.
// settings.gradle.kts (repository root): one build, one project graph
rootProject.name = "orders-platform"
include(":apps:orders-service", ":libs:shared")
// apps/orders-service/build.gradle.kts
plugins {
java
// Replace placeholders with the releases your team targets
id("org.springframework.boot") version "<spring-boot-version>"
id("io.spring.dependency-management") version "<dependency-management-version>"
}
repositories { mavenCentral() }
dependencies {
// No version: resolved from Spring Boot's managed dependencies
implementation("org.springframework.boot:spring-boot-starter-web")
// Gradle project dependency; Nx turns this edge into a project-graph dependency
implementation(project(":libs:shared"))
}
// libs/shared/build.gradle.kts
plugins {
// Plain library jar, no Spring Boot repackaging
`java-library`
}
repositories { mavenCentral() }
dependencies {
// api(...) leaks to consumers' compile classpath; implementation(...) stays internal
}
// Shell, from the repository root:
// gradle wrapper # generates gradlew, gradlew.bat, gradle/wrapper/ (commit them)
// ./gradlew build # confirm the Gradle build works before Nx reads it
// nx add @nx/gradle # installs the plugin and registers it in nx.json
Three Kotlin DSL build files (root settings, Spring Boot service, java-library module) plus the shell steps to generate the wrapper, verify the Gradle build and add @nx/gradle.
How do you verify what Nx inferred from Gradle?
Before wiring anything into CI, check that Nx sees the same project structure Gradle does. Inference runs Gradle under the hood, so a wrong answer here usually means Gradle itself is misconfigured, not Nx.
Start with nx show projects. Every Gradle subproject you expect, such as the Spring Boot service and each shared library, should appear. If one is missing, Nx never received it from Gradle.
Next, run nx show project <name> against the service. This lists the targets Nx created from Gradle tasks (build, test, bootJar and similar) along with the inputs and outputs Nx derived for each. Read the outputs carefully. They determine what Nx restores from cache, and a missing build directory here will matter in the caching section.
Then open nx graph and find the edge from the service to the library. That edge comes from the single implementation(project(":libs:shared")) line in the service's build file. Nx reads Gradle's resolved project dependencies, so this one declaration is the only reason a change to the library marks the service as affected. If the edge is absent, nx affected will skip the service and let a breaking library change through.
When a project or edge is missing, check these in order:
- Settings includes: confirm the subproject is listed in
settings.gradle(.kts). - Gradle errors: run
./gradlew projectsdirectly. Nx swallows configuration failures that Gradle reports clearly. - Version mismatch:
@nx/gradlemust match your corenxversion.
After fixing any of these, run nx reset to clear stale project-graph data.
#!/usr/bin/env bash
# Check what Nx inferred from Gradle before relying on it in CI.
# Project names are placeholders; use the names printed by step 1.
set -euo pipefail
# 1. Every Gradle subproject should appear (service + each shared library).
npx nx show projects
# 2. Inspect the service: which Gradle tasks became targets,
# and the inputs/outputs Nx derived for each. Check outputs carefully,
# since they decide what gets restored from cache.
npx nx show project orders-service --json | jq '.targets | keys'
npx nx show project orders-service --json | jq '.targets.build | {inputs, outputs}'
# 3. Confirm the service -> library edge created by
# implementation(project(":libs:shared")) in the service build file.
npx nx graph --file=graph.json
jq '.graph.dependencies["orders-service"]' graph.json
# 4. Prove the edge matters: touching a library file should list the service.
npx nx show projects --affected \
--files=libs/shared/src/main/java/com/example/shared/Money.java
# --- If a project or edge is missing, check in this order ---
# a) Is the subproject included in settings.gradle(.kts)?
grep -n 'include' settings.gradle.kts
# b) Does Gradle itself configure cleanly? Errors show up clearly here.
./gradlew projects
# c) Do @nx/gradle and nx report the same version?
npm ls nx @nx/gradle
# After fixing anything, clear cached project-graph data and re-check.
npx nx reset
npx nx show projects
A verification script that lists the projects Nx inferred, inspects the service's targets and outputs, confirms the service-to-library edge in the exported graph, and walks through the troubleshooting checks when a project or edge is missing.
How do you run builds, tests and affected targets through Nx and Gradle?
With inference confirmed, day-to-day work runs through three Nx entry points.
nx run-many -t build runs the inferred build target across every project, ordered by the project graph so shared libraries build before the services that consume them. nx run orders-service:test scopes work to one project. The Nx project name may differ from the Gradle path, so check nx show projects instead of guessing. nx affected -t test --base=origin/main runs tests only for projects touched since the merge base with main, plus their dependents. Pass the base explicitly. Otherwise Nx falls back to its configured default, which may not match the branch your pull requests target, and you get either missed tests or a full run.
./gradlew keeps working on its own because Nx calls Gradle rather than replacing it. When results differ between the two paths, such as a test passing under Gradle but failing under Nx, rerun with Gradle directly. If Gradle passes, suspect cache inputs or graph edges, not your code.
| Task | Nx command | Gradle equivalent | Prefer |
|---|---|---|---|
| Build everything | nx run-many -t build |
./gradlew build |
Nx, for caching and cross-language ordering |
| Test one service | nx run orders-service:test |
./gradlew :orders-service:test |
Gradle when iterating on a single class |
| Test changed code | nx affected -t test --base=origin/main |
No direct equivalent | Nx, especially in CI |
| Debug a failure | — | ./gradlew :orders-service:test --info |
Gradle, for full build output |
Agree as a team on which column is canonical locally and which in CI, and write the choice down. If developers use Gradle locally while CI runs Nx, cache and graph problems only show up after merge.
#!/usr/bin/env bash
# Canonical commands, shared by developers and CI so both paths stay identical.
set -euo pipefail
# Confirm the Nx project names inferred from Gradle; they may differ from Gradle paths.
npx nx show projects
# Build every project in project-graph order (shared libs before services).
npx nx run-many -t build
# Run one service's tests through Nx.
npx nx run orders-service:test
# Test only projects changed since the merge base with main, plus dependents.
# Pass the base explicitly so local runs and CI compare against the same branch.
git fetch origin main
npx nx affected -t test --base=origin/main --head=HEAD
# Fallback when Nx and Gradle disagree: run the same task through Gradle directly.
# If this passes but the Nx run fails, inspect cache inputs and graph edges.
./gradlew :orders-service:test --info
# Optional: rerun the Nx target without reading from the cache to rule it out.
npx nx run orders-service:test --skip-nx-cache
A shared script of canonical Nx commands for building, testing one service and testing affected projects against an explicit base, with ./gradlew kept as the direct fallback for debugging differences between the two paths.
How should you configure caching so Nx never replays a stale Spring Boot build?
Nx caches a task only when the target is marked cacheable. Before running it, Nx computes a hash from the declared inputs: source files, named inputs, runtime values and the hashes of dependent tasks. On a hash match, Nx skips Gradle entirely and restores whatever paths the target lists as outputs. If the outputs list build/classes but not build/libs, a cache hit restores compiled classes and no boot jar. The packaging step then fails, or it ships a jar left over from an earlier run.
Undeclared inputs are worse. Suppose a profile-specific application-prod.properties sits outside the input globs, or SPRING_PROFILES_ACTIVE changes behaviour at build time. Nx sees an identical hash and replays an artifact built under different conditions. A slow build costs minutes and is obvious. A false cache hit is silent, passes CI, and surfaces later as a configuration bug in a deployed service.
Run nx show project <name> to see which targets the plugin inferred, with their inputs, outputs and cache flags. Correct them in nx.json under targetDefaults. Add environment inputs for variables that affect the build, extend file inputs to cover resource directories, and set outputs that include the full build/ tree for packaging targets.
| Concern | Gradle incremental build / build cache | Nx task cache |
|---|---|---|
| Granularity | Individual Gradle tasks | Whole Nx target |
| Input tracking | Declared by task implementations | Declared in Nx config |
| Enabled by | Incremental by default; build cache is opt-in | cache flag per target |
| Typical failure | Misconfigured custom task | Missing input or output glob |
Pick one cache to trust for each target and leave the other off for it.
How do you declare dependencies Gradle cannot see?
The project graph that @nx/gradle builds reflects only what Gradle declares: project(...) dependencies, included builds, and the task wiring between them. Anything that crosses the Gradle boundary is invisible to it. That includes generated clients, shared schema or resource files read from a relative path, Dockerfiles that copy a jar from another module, and any npm project that consumes a JVM artifact. A missing edge produces no error. nx affected simply skips a project that should have been tested, and CI goes green on a broken contract.
Example: an OpenAPI client consumed by a frontend
Take an orders-service Spring Boot project whose Gradle build writes an OpenAPI spec, an orders-client TypeScript project generated from that spec, and a web frontend that imports the client. Nx can already see web → orders-client through the package import. It cannot see orders-client → orders-service.
Declare that edge in two places in the client's project.json:
implicitDependencies: ["orders-service"]adds the edge to the graph. Changes to the service then mark the client, and transitivelyweb, as affected.- A
dependsOnentry on the client'sgeneratetarget points at the service's spec-producing task, using the object form withprojectsandtarget. Without it, Nx may run generation against a stale or missing spec, because nothing orders the two tasks. Also list the spec file in the target'sinputsso a changed spec invalidates the cached client.
To verify, run nx graph and confirm the client-to-service edge appears. Then touch a controller in orders-service and run nx show projects --affected. Both orders-client and web should be in the output. If they are missing, the edge is not being picked up.
Setting up CI and packaging the Spring Boot jar
A CI job for this workspace needs two runtimes: a JDK that matches the Gradle toolchain and Node for Nx itself. Install both, then restore the caches your team actually uses. That usually means the Gradle user home (dependencies and wrapper distributions) and, if you use it, Nx's local cache directory or remote cache. Fetch full git history, or at least enough to reach the merge base. nx affected compares --base against --head, and a shallow clone makes that comparison fail or silently widen to everything. Then run nx affected -t build test instead of building every project.
Ephemeral runners have fixed memory, and each Gradle invocation Nx starts may spawn or reuse a daemon with its own heap. Set org.gradle.jvmargs in gradle.properties with an explicit -Xmx so memory use is predictable. Then cap Nx with --parallel so that concurrent Gradle processes multiplied by heap size stays below what the runner provides. If you skip this, you get intermittent out-of-memory kills that look like flaky tests.
Graph computation runs Gradle configuration, so keep build scripts lean. Avoid network calls, heavy plugin logic, and eager task creation at configuration time.
For packaging, let Gradle own it. Run the inferred build or bootJar target through Nx and pick up the executable jar from build/libs in the service directory. Your java -jar step or container build should copy from that path, not from a new Nx target that re-implements the packaging.
What are the alternatives to the Nx Gradle plugin for a Java monorepo?
None of these options is free. Each one moves cost between tooling setup and engineer time.
| Approach | Affected detection | Caching | Cross-language dependency visibility | Setup and maintenance cost | Developer experience |
|---|---|---|---|---|---|
| Gradle-only multi-project build | None based on git; up-to-date checks skip unchanged work | Gradle build cache, local or remote | JVM only | Low if the team already knows Gradle | Familiar to Java engineers; frontends need a separate toolchain |
| Separate repositories | Per repository only | Per repository toolchain | None; contracts drift silently | Low per repo, high coordination cost | Simple locally; cross-cutting changes need several PRs |
Manual run-commands wrapping ./gradlew |
Works, but project dependencies are declared by hand | Nx cache, correct only if inputs and outputs are kept accurate | Yes, if kept in sync manually | Grows with every new module | One command surface; stale configuration causes wrong cache hits |
@nx/gradle inference |
Derived from the Gradle project graph | Nx cache plus Gradle's own | Yes | Moderate setup, low ongoing | One command surface with little hand-written configuration |
A JVM-only team with no frontend in the repository gains little from Nx. Gradle's build cache and up-to-date checks already avoid repeated work. Separate repositories suit teams that rarely change the API and its consumers together. Manual run-commands is a reasonable bridge for two or three services, but every hand-written dependency or input list can go stale. When it does, the cache can replay a wrong result. Inference makes sense once one team regularly changes Java and TypeScript code in the same pull request. The time saved by accurate affected runs grows with every service, while the plugin's overhead stays roughly fixed.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to nx gradle plugin spring boot, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.