What is the Nx Gradle plugin and how does it work with Spring Boot?

The Nx Gradle plugin adds Nx's project graph and task scheduling to a Gradle build. Gradle still compiles code, resolves dependencies, applies the Spring Boot plugin and runs the build lifecycle. Nx sits above it. It asks Gradle which projects and tasks exist, builds a graph from that answer, and then decides which tasks to run and in what order. Your build.gradle.kts files stay as they are, and nothing about how a Spring Boot jar is produced moves into Nx.

This split matters because each tool keeps one job. Gradle understands Java classpaths, annotation processing and Boot packaging. Nx understands which projects a change touches and how to schedule work across the whole repository, including projects that are not Java.

The running example is a three-project build:

  • common-domain is a plain Java library with shared entities and value types.
  • orders-service is a Spring Boot application that declares project(":common-domain").
  • billing-service is a Spring Boot application with the same dependency.

All three are included in settings.gradle.kts and built with the Gradle wrapper. Nx calls that same wrapper, so local runs and CI use one Gradle version.

The layers connect like this:

Gradle build files (settings.gradle.kts, build.gradle.kts) ↓ inference: Nx runs Gradle to read projects, tasks and dependencies Nx project graph (orders-service → common-domain ← billing-service) ↓ scheduling: Nx picks tasks and their order Gradle task execution (for example, :orders-service:test)

Because Nx gets its graph from Gradle, the graph can only be as accurate as your Gradle dependency declarations.

// settings.gradle.kts: registers every project. Nx learns the project list from Gradle, not from this file directly.
rootProject.name = "shop"

include(":common-domain")
include(":orders-service")
include(":billing-service")

// common-domain/build.gradle.kts: plain Java library with shared entities
plugins {
    `java-library`
}

// orders-service/build.gradle.kts: Spring Boot app. Gradle still owns packaging.
plugins {
    java
    // Plugin versions come from gradle/libs.versions.toml
    alias(libs.plugins.spring.boot)
    alias(libs.plugins.spring.dependency.management)
}

dependencies {
    // This declaration becomes the edge orders-service -> common-domain in the Nx graph.
    // If it is missing here, Nx cannot know about the dependency.
    implementation(project(":common-domain"))
    implementation("org.springframework.boot:spring-boot-starter-web")
    testImplementation("org.springframework.boot:spring-boot-starter-test")
}

// billing-service/build.gradle.kts uses the same plugins and the same
// implementation(project(":common-domain")) line, which gives the second edge.

These Gradle Kotlin DSL files are the only source Nx reads for its graph: include defines the three projects, and each project(":common-domain") dependency becomes one edge.

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

Nx earns its place when one repository holds more than one build tool. If your Spring Boot services sit next to a TypeScript frontend or shared Node tooling, Nx gives you one graph, one affected command and one cache across both. It also helps a pure-Java repo when CI time is the main complaint and most pull requests touch only a few modules. Running only the affected projects then removes whole Gradle invocations rather than only skipping up-to-date tasks.

If the repo is Gradle-only and builds are already fast, Gradle's task graph, configuration cache and build cache probably cover what you need. Adding Nx there brings costs and little benefit:

  • A second tool: you add a Node.js runtime, a package.json and a lockfile to a JVM repo.
  • Inference cost: Nx has to ask Gradle for project and task data. That means Gradle configuration runs before Nx can schedule anything, and the cost grows with the number of projects.
  • Harder-to-read errors: a misconfigured build.gradle.kts can show up as a graph or inference error in Nx instead of a plain Gradle failure.
  • Two entry points: if some people run ./gradlew and others run nx, they get different caching and different scheduling. The team needs to agree on which command is canonical.
Approach Setup cost Affected detection Cross-language orchestration Maintenance burden
Plain Gradle + build cache Low None; up-to-date checks only None Low
Gradle + custom changed-module scripts Medium Hand-rolled, often misses transitive dependencies Manual High; you own the scripts
Nx on top of Gradle Medium Built in, uses the graph inferred from Gradle Yes Medium; two toolchains to keep current

How do you add Nx to an existing Spring Boot Gradle repository?

Before you start, confirm three things work on their own: the Gradle wrapper (./gradlew build succeeds from the repository root), a JDK that matches your Spring Boot toolchain, and Node.js, which runs the Nx CLI. Nx does not replace any of these. It calls into them, so if ./gradlew is broken, Nx inherits the breakage.

If the repository has no package.json yet, run npx nx init at the root to create a minimal Nx workspace. Then run nx add @nx/gradle. This installs the plugin package and registers it in the plugins array of nx.json. That registration is the whole integration. You write no project.json per service, and you don't list modules by hand.

The plugin discovers projects by invoking Gradle and reading what it reports. Every Gradle project in settings.gradle or settings.gradle.kts becomes an Nx project. Its Gradle tasks, such as build, test and bootJar, become Nx targets. Its implementation and api dependencies on sibling projects become edges in the graph. This is why the first Nx command after setup can be slow: Gradle has to configure the build before Nx can build the graph. When you add a new Spring Boot service to the Gradle settings file, Nx picks it up the next time it recomputes the graph, with no Nx-side change.

Pin exact versions of nx and @nx/gradle in package.json, without caret ranges, and keep the two packages on the same version. Because projects and targets are inferred, a plugin upgrade can rename targets or change which tasks are exposed. That would silently break CI scripts that call targets by name. Upgrade deliberately with nx migrate and review the changes it generates.

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

# 1. Check that the prerequisites work without Nx. Nx calls into them.
./gradlew build      # the Gradle wrapper must succeed from the repo root
java -version        # JDK that matches the Spring Boot toolchain
node --version       # Node.js runs the Nx CLI

# 2. Create a minimal Nx workspace if there is no package.json yet.
npx nx init

# 3. Install the Gradle plugin and register it in nx.json "plugins".
npx nx add @nx/gradle

# 4. Check what the plugin inferred by invoking Gradle.
#    No project.json files were written. Projects come from settings.gradle(.kts).
npx nx show projects
npx nx show project orders-service   # inferred targets, e.g. build, test, bootJar

# 5. Confirm the versions in package.json are exact (no ^ or ~)
#    and that nx and @nx/gradle match.
npm pkg get devDependencies.nx 'devDependencies["@nx/gradle"]'

# 6. Later: upgrade deliberately, then review the generated changes.
npx nx migrate latest            # updates package.json, may write migrations.json
npm install
npx nx migrate --run-migrations  # apply the migrations, then review the diff
git diff -- package.json nx.json

This shell session checks the prerequisites, adds @nx/gradle to an existing Spring Boot Gradle repository, inspects the inferred projects and targets, and upgrades the pinned Nx versions with nx migrate.

How do you check that the Nx project graph matches your Gradle dependencies?

Start with nx show projects. It should list one Nx project for each Gradle subproject you expect, such as orders-service and common-domain. If a subproject is missing, Nx did not detect it. The usual cause is that settings.gradle(.kts) does not include it, so fix that before going further.

Next, open nx graph. The plugin asks Gradle for each project's dependencies. A declaration like implementation(project(":common-domain")) in orders-service becomes an edge from orders-service to common-domain. Check every edge against what you intended, not just against what the build files currently say. The graph often exposes problems that compilation hides:

  • A leftover dependency nobody uses anymore.
  • A service that depends on another service instead of a shared library.
  • A cycle.

Nx uses these edges to decide what is affected by a change, so any mistake here makes affected builds wrong.

Then run nx show project orders-service, which also accepts --web for a browser view. It lists the targets Nx inferred and the Gradle task each one invokes through the wrapper. Target names often mirror Gradle task names, but treat that as something to verify rather than assume. Which Gradle tasks become targets depends on the plugin's configuration and version.

Once you have the real names, run work through Nx:

  • nx run orders-service:<target> for one project.
  • nx run-many -t <target> across all projects that define that target.

Copy target names from the nx show project output; don't recall them from memory. For CI, consider generating target lists from nx show project <name> --json so a renamed target causes a visible failure. A hard-coded name that silently matches nothing is much harder to notice.

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

# 1. Each Gradle subproject in settings.gradle(.kts) should appear here.
nx show projects

# 2. Export the dependency graph and list orders-service's outgoing edges.
#    Compare these against the dependencies you intended.
nx graph --file=graph.json
jq -r '.graph.dependencies["orders-service"][].target' graph.json

# 3. List the targets Nx inferred for the project. Use these names.
#    Do not assume they match the Gradle task names.
nx show project orders-service --json | jq -r '.targets | keys[]'

# 4. Pick a target name from the step 3 output. Fail if it is not defined,
#    so a renamed target breaks CI instead of matching nothing.
TARGET="${1:?usage: $0 <target-name-from-nx-show-project>}"
if ! nx show project orders-service --json \
    | jq -e --arg t "$TARGET" '.targets | has($t)' > /dev/null; then
  echo "Target '$TARGET' is not defined for orders-service" >&2
  exit 1
fi

# 5. Run the target for one project, then for every project that defines it.
nx run "orders-service:$TARGET"
nx run-many -t "$TARGET"

This script lists detected projects and prints orders-service's graph edges and inferred targets. It stops with an error if the requested target does not exist, and otherwise runs that target through Nx.

How do affected-only builds save engineering time in a Spring Boot monorepo?

Run the payoff against the running example. Edit a class in common-domain and run nx affected -t test --base=main. Nx diffs your branch against main, maps the changed files to common-domain, and walks the graph upward. Both billing-service and orders-service depend on it, so all three projects run tests. Revert that change, edit only a controller in billing-service, and run the same command. Now only billing-service is tested. orders-service is skipped because no path in the graph connects it to the change.

Illustrative estimate (assumed numbers, not a benchmark)

Assume these test durations: common-domain takes 2 min, billing-service 6 min and orders-service 8 min, so a full run takes 16 min. Assume 40 PRs per week. Of those, 25% touch common-domain (16 min each), 37.5% touch only billing (6 min) and 37.5% touch only orders (8 min).

Weekly minutes saved = PRs × Σ(share × (full − affected)) = 40 × (0.25×0 + 0.375×10 + 0.375×8) = 270 min per week.

To estimate cost, multiply the saved minutes by your runner's per-minute price. The savings grow with the number of services and shrink as more changes land in shared modules.

Where affected misses changes

Nx only sees dependencies that Gradle declares. The following couplings will not trigger a rerun:

  • Runtime calls. One service calls another over REST, or they exchange Kafka messages.
  • Shared config. A shared application.yml or contract file sits outside any project.
  • Published artifacts. A module is consumed by Maven coordinates rather than as a project dependency.

In these cases orders-service stays green while the API it calls has changed underneath it. Contract tests or a periodic full run are the backstop.

# Scenario 1: change a shared module and confirm both services are selected.
git checkout -b feature/money-rounding main
# Edit a class in common-domain (placeholder path for the running example)
echo '// rounding tweak' >> common-domain/src/main/java/com/example/domain/Money.java
git commit -am "Adjust Money rounding"

# List the projects Nx considers affected relative to main
nx show projects --affected --base=main
# Expected: common-domain, billing-service, orders-service

# Run tests only for those projects
nx affected -t test --base=main

# Scenario 2: change only billing-service and confirm orders-service is skipped.
git checkout main
git checkout -b feature/billing-endpoint
echo '// new endpoint' >> billing-service/src/main/java/com/example/billing/InvoiceController.java
git commit -am "Add invoice endpoint"

nx show projects --affected --base=main
# Expected: billing-service only. No graph edge leads from it to orders-service.

nx affected -t test --base=main

# Backstop for couplings Gradle cannot see (REST, Kafka, shared config,
# modules consumed by Maven coordinates): run every project's tests on a
# schedule, for example nightly in CI.
nx run-many -t test

Shell session that edits common-domain and then billing-service only, uses nx show projects --affected and nx affected -t test --base=main to show which Spring Boot projects are selected each time, and runs nx run-many as a periodic full run to catch dependencies the Gradle graph misses.

How does Nx caching interact with Gradle's build cache?

Nx's cache sits one level above Gradle. When Nx runs a target such as orders-service:build, it hashes the target's declared inputs. On a hit it skips Gradle entirely and restores the recorded terminal output and declared output files. On a miss it invokes Gradle, which then applies its own up-to-date checks and build cache per task. A single build can therefore hit one layer and miss the other, and each layer is only as correct as its declared inputs.

Layer Scope Cache key Where outputs live Typical failure mode
Nx task cache Whole Nx target, which may span many Gradle tasks Hash of configured input files, env vars and dependency outputs Nx cache directory, or remote cache, restored to declared output paths Stale hit after a version catalog, buildSrc or gradle.properties change that was not declared as an input. Or a "hit" that restores logs but no boot jar, because build/libs was not declared as an output
Gradle up-to-date checks Single task, local workspace Input/output fingerprints from the last run Project build/ directory Custom tasks with undeclared inputs
Gradle build cache Single task, local or remote Task input fingerprint Gradle local cache or remote node Misses caused by absolute paths or non-reproducible archives, such as jars that embed file timestamps

Before you trust cache hits, verify the inputs and outputs. Delete build/, replay a cached target, and confirm that the boot jar and build/test-results actually reappear.

Make one layer the source of truth for caching:

  • Gradle build cache: If your team already runs a Gradle remote cache, disable Nx caching for Gradle targets. Use Nx only for the project graph and affected selection.
  • Nx cache: If you have no Gradle remote cache, rely on the Nx cache, and keep its input list in sync with your build logic.

How do you run a polyglot monorepo with Java services and TypeScript in one CI pipeline?

A TypeScript frontend or generated API client can live in the same project graph as your Spring Boot services. Nx's JavaScript tooling infers those projects from package.json and workspace configuration, and the Gradle plugin infers the Java side. One nx affected command can then cover both languages. The gap is any edge that crosses languages. Nx cannot see that a frontend consumes an OpenAPI spec generated by orders-service, because nothing in the Gradle files or package.json records that link. Declare it explicitly with implicitDependencies in the frontend's project configuration. You can also make the client's codegen target depend on the service target that writes the spec. Either way, a controller change in the service marks the frontend as affected.

A CI pipeline needs four steps, whatever system runs it:

  1. Check out enough history. Nx needs the merge base between the current commit and the base ref. A shallow clone can't resolve it, so the comparison either fails or treats everything as changed. Fetch full history, or at least enough depth to include the merge base.
  2. Choose a base ref. On pull requests, use the target branch. On main, use the last commit that passed CI, not HEAD~1, so a failed run's changes get rebuilt.
  3. Set up the JDK and Node with your usual dependency caching.
  4. Run nx affected -t lint test build.

When the graph looks wrong

  • Is the module included in settings.gradle.kts?
  • Are internal dependencies declared with project(":lib"), not group:artifact:version coordinates, which Nx treats as external?
  • Did build logic change? Reset the Nx cache and daemon so inference runs again.
  • Do buildSrc, convention plugins or composite builds need targets configured explicitly?
  • After an Nx upgrade, do inferred target names still match your CI commands?

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.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

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.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • 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.