What is @nx/gradle and how does it work with a Spring Boot build?

@nx/gradle is an Nx plugin that treats your existing Gradle build as the source of truth. When Nx computes its project graph, the plugin runs Gradle through the wrapper (./gradlew) and reads Gradle's own project model. Each subprojects included in settings.gradle(.kts) becomes an Nx project, and Gradle tasks such as build, test and bootRun become Nx targets. Dependencies declared between subprojects, like a service depending on project(":shared-lib"), become edges in the Nx graph. You do not write a project.json per service. Nx infers the structure from the build you already maintain, so the two cannot drift apart.

This article divides the responsibilities this way. Gradle owns compilation, packaging and its build cache. The Spring Boot plugin still produces the jar, and Gradle still decides what is up to date. Nx owns the project graph, task orchestration and affected detection. It decides which projects a change touches and in what order to run their tasks. Nx does not replace Gradle. When Nx runs a target, it invokes Gradle to do the work.

 settings.gradle(.kts)
   ├─ :orders-service  (Spring Boot)
   ├─ :billing-service (Spring Boot)
   └─ :shared-lib
          │
          ▼
 Gradle project model  ◄── ./gradlew <task>
 (projects, tasks, deps)
          │  read by @nx/gradle
          ▼
 Inferred Nx graph     ◄── nx run / nx affected
 (projects, targets, edges)

Inferred target names and plugin options have changed between Nx releases. Check the @nx/gradle documentation for the version you install before copying target names into scripts or CI.

+-----------------------------------------------------+
| settings.gradle(.kts)                               |
|   :orders-service   (Spring Boot)                   |
|   :billing-service  (Spring Boot)                   |
|   :shared-lib       (library)                       |
+-----------------------------------------------------+
                          |
                          v
+-----------------------------+     +------------------+
| Gradle project model        |<----| ./gradlew <task> |
|  projects, tasks, deps      |     |  (Gradle CLI)    |
|  Gradle owns: compile,      |     +------------------+
|  package (Boot jar), cache  |
+-----------------------------+
     |                   ^
     | @nx/gradle reads  | Nx runs targets
     | the model via     | by invoking
     | ./gradlew         | ./gradlew
     v                   |
+-----------------------------+     +----------------------+
| Inferred Nx graph           |<----| nx run / nx affected |
|  subprojects -> projects    |     |  (Nx CLI)            |
|  Gradle tasks -> targets    |     +----------------------+
|  project(":x") -> edges     |
|  Nx owns: graph, task       |
|  orchestration, affected    |
+-----------------------------+

@nx/gradle reads Gradle's project model through the wrapper to infer the Nx graph, where Nx orchestrates tasks and Gradle builds.

Who should add Nx to a Java monorepo, and when should you avoid it?

Nx earns its place when the repository is not only Java. If Spring Boot services share a repository with a TypeScript frontend, a Node BFF or generated API clients, Nx gives you one project graph and one affected command across all of them. That matters most when CI time is the bottleneck: on a pull request that touches only a React component, Nx can skip every Gradle project. Teams already running Nx for frontends also avoid a second orchestration tool.

For JVM-only teams, the case is weaker. Gradle's build cache already avoids re-running tasks whose inputs are unchanged, the configuration cache cuts startup cost, and multi-project or composite builds model inter-module dependencies natively. Adding Nx on top brings real costs:

  • Two mental models. Engineers have to reason about Nx targets and Gradle tasks, and about which cache produced a given result.
  • Two sets of configuration. Some settings live in nx.json and project.json, and others live in build.gradle.kts, so they can drift apart.
  • Graph-computation overhead. Nx invokes Gradle to discover projects and tasks, which adds latency when the graph is recalculated.
  • Fragility. Build scripts that resolve dependencies or do I/O during the configuration phase make graph extraction slow and error-prone.
Nx + Gradle Gradle multi-project Gradle composite build
Graph visibility Cross-language graph and UI Gradle projects only Separate builds, linked
Affected detection Built in, Git-based None built in None built in
Caching layers Nx cache plus Gradle caches Gradle build and configuration cache Gradle caches per build
Polyglot support First-class JVM-centric JVM-centric
Maintenance cost Highest Lowest Moderate

Setting up an Nx Java monorepo with Spring Boot services and a shared library

Start from a plain Gradle multi-project build and add Nx on top; Nx does not replace any of it. A workable layout has services/orders, services/billing and libs/shared under one root, a single Gradle wrapper at the root, and one settings.gradle.kts that calls include for each subproject. Keep the wrapper at the root so every service builds with the same Gradle version and Nx has one entry point to invoke.

Wire the services to the shared library

In each service's build.gradle.kts, apply the Spring Boot plugin and declare implementation(project(":shared")), adjusting the path to match how you named the project in settings. This dependency matters twice. Gradle uses it to order compilation, and @nx/gradle reads it to draw an edge in the Nx project graph. That edge is what later lets Nx mark both services as affected when only shared changes. Apply the java-library plugin to shared rather than the Spring Boot plugin, so it produces an ordinary jar instead of an executable one.

Initialize Nx

Run npx nx init at the repository root. Recent versions detect Gradle and offer to add @nx/gradle. If yours doesn't, npx nx add @nx/gradle installs the package and adds it to the plugins array in nx.json. Option names for the plugin entry have changed between releases, so check them against the docs for your installed Nx version before editing.

Why settings.gradle.kts decides what Nx sees

@nx/gradle does not scan the directory tree for build files. It asks Gradle for its project model. Gradle only knows about projects that settings.gradle.kts includes. A directory that has a valid build.gradle.kts but is missing from settings is not a project to Gradle, so Nx never sees it. If a service is missing from nx show projects, check settings first.

# Run from the repository root.
# 1. Declare every subproject. Anything not included here is not a Gradle
#    project, so @nx/gradle will never report it to Nx.
cat > settings.gradle.kts <<'EOF'
rootProject.name = "acme-platform"
include(":services:orders", ":services:billing", ":libs:shared")
EOF

# 2. Shared library: a plain jar, not a Spring Boot executable.
cat > libs/shared/build.gradle.kts <<'EOF'
plugins { `java-library` }
EOF

# 3. A service depends on the shared library. Gradle uses this edge for
#    build order; @nx/gradle uses it to draw the Nx project graph edge.
#    Replace the plugin versions with the ones your team has pinned.
cat > services/orders/build.gradle.kts <<'EOF'
plugins {
    java
    id("org.springframework.boot") version "3.3.0"
    id("io.spring.dependency-management") version "1.1.5"
}
dependencies {
    implementation(project(":libs:shared"))
    implementation("org.springframework.boot:spring-boot-starter-web")
}
EOF
# (repeat step 3 for services/billing)

# 4. Add Nx on top of the existing Gradle build.
npx nx init
npx nx add @nx/gradle   # only if init did not register the plugin

# 5. Verify: every subproject from settings should appear here.
npx nx show projects

Settings include all three subprojects, the orders service depends on the shared library, and Nx is added with @nx/gradle, then checked with nx show projects.

How do you run Spring Boot build, test and bootRun tasks through Nx?

Inferred targets carry the same names as the Gradle tasks they wrap, so a service with the Spring Boot plugin applied exposes build, test and bootRun without any extra configuration. Run nx show project service-a to list exactly what was inferred before you script against it. Nx still calls Gradle to do the work. What Nx adds is the decision about which projects to run, in what order, and whether a cached result can be reused.

Nx command Plain Gradle equivalent
nx run service-a:build ./gradlew :service-a:build
nx run service-a:test ./gradlew :service-a:test
nx run-many -t build ./gradlew build
nx run-many -t test -p service-a,service-b ./gradlew :service-a:test :service-b:test
nx run service-a:bootRun ./gradlew :service-a:bootRun

Gradle task paths follow the project path in settings.gradle.kts. A service nested under services/ may therefore be :services:service-a in Gradle, while Nx uses its own project name.

Keep the Gradle column within reach, because some tasks don't fit Nx's model well:

  • bootRun and other long-running tasks: They never finish, so there is nothing to cache.
  • Finalizers (finalizedBy) and ordering rules (mustRunAfter): Gradle resolves these inside a single invocation. Splitting that invocation into separate Nx targets can lose them.
  • Custom aggregate lifecycle tasks: They express "run all of these" in Gradle terms.

For these cases, use Gradle directly. You lose nothing by doing so.

Finally, run nx graph and find service-a. It should have an edge pointing to shared-lib. If that edge is missing, Nx won't rebuild the service when the library changes. Check that the service declares the library with implementation(project(":shared-lib")) rather than consuming a published artifact.

#!/usr/bin/env bash
set -euo pipefail

# 1. List the targets Nx inferred from the Gradle build before scripting against them.
nx show project service-a

# 2. Cacheable, finite tasks go through Nx.
#    Nx picks the projects, orders them and replays cached results; Gradle does the work.
nx run service-a:build
nx run-many -t test -p service-a,service-b
nx run-many -t build

# Plain Gradle equivalents, which are always available as a fallback.
# Use the Gradle project path from settings.gradle.kts, e.g. :services:service-a.
./gradlew :service-a:build
./gradlew :service-a:test :service-b:test

# 3. Run long-running or ordering-sensitive work with Gradle directly.
#    A single invocation keeps finalizedBy and mustRunAfter rules intact,
#    and a bootRun process never finishes, so there is nothing for Nx to cache.
./gradlew :service-a:bootRun --args='--spring.profiles.active=local'

# 4. Inspect the project graph visually and focus on the service.
nx graph --focus=service-a

# Or export the graph and check for the service-a -> shared-lib edge in a script.
nx graph --file=graph.json
if jq -e '.graph.dependencies["service-a"][] | select(.target == "shared-lib")' graph.json > /dev/null; then
  echo "OK: service-a depends on shared-lib"
else
  echo "Missing edge: check implementation(project(\":shared-lib\")) in service-a" >&2
  # Confirm what Gradle itself resolves.
  ./gradlew :service-a:dependencies --configuration runtimeClasspath
  exit 1
fi

A shell session that runs inferred targets through Nx, falls back to plain Gradle for bootRun and ordering-sensitive tasks, and checks that the service-a to shared-lib edge appears in the Nx project graph.

How do Nx affected commands and caching work for Gradle projects in CI?

nx affected -t test compares the current commit against a base ref, maps changed files to projects, and runs test only for those projects and their dependents. A change to shared-lib therefore tests every service that depends on it, while an edit confined to one service tests only that service.

The comparison needs git history. A depth-1 clone has no merge base, so Nx cannot compute what changed. Fetching full history fixes this but slows checkout in large repositories. A common middle ground is to fetch only enough history to reach the base. Pick an explicit base ref, such as the merge base with main for pull requests or the last successful commit on main for branch builds. Also decide on a fallback: when the base can't be resolved, run all projects. Running too much is slower, but silently running nothing is worse.

Caching layers

Layer Owns Keyed on
Nx cache Terminal output and declared outputs of a whole target Inputs declared or inferred for the project
Gradle build cache Outputs of individual tasks, such as compiled classes and jars Gradle's per-task input fingerprints
Incremental compilation Recompiling only the classes affected by a change Source and classpath changes

The Nx cache only skips a target on an exact hit. When it misses, Gradle's caching and incremental compilation still decide how much work runs. Keep them enabled.

The main risk is a false green. If a file that affects the result, such as application.yml or a version catalog, is missing from the target's inputs, Nx replays a stale pass. Missing outputs cause the opposite problem: a cache hit that restores no artifacts. For tests that depend on databases, Testcontainers or the network, external state is not part of the cache key, so disable caching for those targets.

A remote cache adds two more questions to answer: who can write to it, and how restored artifacts are validated before you trust them.

#!/usr/bin/env bash
# CI step for pull requests: test only affected Gradle projects,
# and fall back to testing everything if the base can't be resolved.
set -euo pipefail

BASE_BRANCH="${BASE_BRANCH:-main}"
MAX_DEEPEN_ROUNDS=5

# Start shallow to keep checkout fast. Fetch the base branch tip so
# origin/main exists locally.
git fetch --no-tags --depth=50 origin "$BASE_BRANCH"

# Deepen in steps until the PR head and the base share a merge base.
# Stop after a fixed number of rounds instead of pulling full history.
for _ in $(seq 1 "$MAX_DEEPEN_ROUNDS"); do
  if git merge-base HEAD "origin/$BASE_BRANCH" >/dev/null 2>&1; then
    break
  fi
  git fetch --no-tags --deepen=200 origin "$BASE_BRANCH"
done

if BASE_SHA=$(git merge-base HEAD "origin/$BASE_BRANCH" 2>/dev/null); then
  echo "Affected base: $BASE_SHA"
  # Runs 'test' for changed projects and every project that depends on them.
  npx nx affected -t test --base="$BASE_SHA" --head=HEAD
else
  # No merge base: run everything. Slower, but it can't silently skip tests.
  echo "warning: no merge base with origin/$BASE_BRANCH; running all tests" >&2
  npx nx run-many -t test
fi

A pull request CI script that fetches only as much git history as it needs to find the merge base with main, runs nx affected -t test against that base, and runs every project's tests when no merge base can be found.

How do you override inferred targets and add cross-language dependencies in a polyglot workspace?

Inferred targets cover the standard Gradle lifecycle, but most real builds deviate somewhere. If you've added an integrationTest task backed by its own source set, Nx sees the task but has no way to know which directories feed it or what it writes. There are two places to fix this. Use the @nx/gradle plugin options in nx.json for workspace-wide conventions, such as renaming targets so every service exposes the same name. Use a project's project.json for one-off cases. Nx merges per-project target configuration over the inferred target, so you only declare the fields you are changing, usually inputs and outputs.

Inputs also need to cover files that Gradle doesn't model as dependencies. Examples include a shared application-common.yml, a checked-in OpenAPI spec that feeds code generation, a Dockerfile, or Helm chart values. Add them as file inputs, such as {workspaceRoot}/config/**, or as a named input reused across targets. This way a change to them invalidates the cache and marks dependent projects as affected.

Adding a TypeScript frontend works the same way. Once it is registered as a project, nx affected -t build test covers both the JVM services and the UI in a single run. Nx cannot see that the frontend's generated client comes from the API contract module, so declare that link with implicitDependencies in the frontend's project configuration.

Test any missing link before you rely on it. If a dependency is undeclared, Nx doesn't report an error. It decides the project is unaffected and skips it, and a passing CI run can hide that the work never ran.

How can you verify the setup and tell whether Nx is saving engineering time?

Correctness checklist

Run these checks before you trust a green pipeline:

  • Every service appears in the graph. nx show projects should list each Gradle subproject. A missing service usually means the plugin did not pick up its build file.
  • Targets map to the right Gradle tasks. nx show project <name> shows what each target runs. Confirm that build, test and bootRun call the intended tasks on the intended subproject.
  • Shared-library changes fan out. Make a trivial edit in the shared library on a branch, then run nx show projects --affected. Every service that depends on the library must be listed.
  • Gradle still works without Nx. A plain ./gradlew build must pass. If it doesn't, you have tied correctness to Nx and lost your fallback.

Weighing cost against benefit

Illustrative estimate (assumed numbers, not a benchmark): 12 services, 6 min average test time each, 70% of PRs touch one service, 1 min graph overhead.

  • Without Nx: 12 × 6 = 72 min per PR.
  • With Nx: p × (t + o) + (1 − p) × (N × t + o) = 0.7 × 7 + 0.3 × 73 ≈ 27 min.

These are serial compute minutes. Parallel runners change wall-clock time but not cost. Compare against a tuned Gradle setup with its build cache enabled, because that cache already skips some of this work.

What to track in your own CI

  • Median and p90 pipeline duration.
  • Cache hit rate.
  • Runner minutes per PR.
  • Number of escaped defects traced to wrongly skipped projects.

If the savings stay small or skips cause defects, go back to Gradle alone.

Alternatives to consider

Gradle on its own

If the workspace is Java-only, Gradle already covers much of what Nx adds. Its build cache, local or remote, reuses task outputs across machines. The configuration cache cuts startup time on large builds. Up-to-date checks skip unchanged work within a single build. Convention plugins in an included build-logic build keep Spring Boot settings consistent across services.

Gradle has no built-in equivalent of nx affected. Teams usually approximate it with a script that maps git diff paths to subprojects and walks the project dependency graph. This works, but you have to maintain it yourself, and it tends to miss edges such as shared resources and version catalogs.

CI path filters

Most CI systems can trigger jobs based on changed paths. This is cheap and needs no new tooling. However, path filters know nothing about the dependency graph. A change in a shared library will not rebuild the services that consume it unless someone keeps the filter lists in sync by hand. That manual sync is exactly how wrongly skipped projects slip through.

A hermetic polyglot build system

Build systems that declare every input explicitly give you stronger correctness guarantees and fine-grained remote caching across languages. The cost is high. You rewrite build definitions, lose the Spring Boot Gradle plugin's conventions, and need dedicated build expertise. This is justified mainly when the repository is very large and build correctness problems are frequent.

Separate repositories

Splitting services into their own repositories with published library artifacts removes the need for an orchestrator altogether. In exchange, cross-service changes require coordinated releases.

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 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.