Keeping Spring Boot Code Clean and Consistent with Spotless Maven

In this post, we’ll set up the Spotless Maven plugin on a Spring Boot 4 / Java 25 project so that formatting is applied by a tool, checked in CI, and no longer discussed in code review.


Prerequisites

This is the list of all the prerequisites:

  • Spring Boot 4+
  • Maven 3.9.x
  • Java 25
  • Spotless Maven plugin 3.11.0
  • An IDE (IntelliJ IDEA, VS Code or Eclipse)

Concept Overview

Every Spring Boot team ends up having the same argument sooner or later. Tabs or spaces, where the imports go, how long a line can be, whether the { belongs on its own line. Nobody wins, and the cost shows up in pull requests: a 12-line bug fix turns into a 400-line diff because someone’s IDE reformatted the whole file on save.

We’ll configure Java, pom.xml, YAML and Markdown formatting, wire it into GitHub Actions, and look at the parts that bite in production: legacy codebases, IDE drift, JDK 25 warnings and CI shallow clones.

What Spotless is

Spotless is a formatter orchestrator. It does not ship its own Java style. It calls existing formatters such as google-java-format, palantir-java-format, Eclipse JDT or Prettier, and adds generic steps on top (trailing whitespace, license headers, import ordering, regex rules).

The Maven plugin exposes three goals you will use daily:

The mental model

Spotless is built around formats. Each format has two things:

  1. a target: the files it applies to (includes / excludes)
  2. an ordered list of steps: each step is a String -> String function
┌──────────────────────── <java> format ─────────────────────────────────────────────────────────────┐
Foo.java ─▶│ toggleOffOn → palantirJavaFormat → importOrder → ... → header │─▶ formatted Foo.java
└────────────────────────────────────────────────────────────────────────────────────────────────────┘

spotless:apply writes the output back to disk. spotless:check compares the output with what is on disk and fails if they differ.

Two consequences matter in practice:

  • Order matters. If you put a custom <indent> step before google-java-format, the formatter overwrites it. Put steps that adjust a formatter’s output after the formatter.
  • Steps must be idempotent. Running apply twice must give the same result. If two steps fight each other (one adds a blank line, the next removes it), check will never pass. Spotless detects this and reports it.

Why not just use IDE settings?

IDE formatters only run when someone presses the shortcut, they differ between IntelliJ, Eclipse and VS Code, and they are not checked in CI. A shared .editorconfig helps, but it only covers indentation and whitespace, not import order or line wrapping. Spotless moves formatting into the build, where it is versioned, reviewed and enforced the same way for everyone.

What We’re Building

We will add Spotless to a small product catalog REST API:

┌───────────────────────────────────────────────────────────────────────┐
HTTP ───────▶ │ ProductController (/api/v1/products) │
│ │ │
│ ProductService (duplicate SKU, paging rules) │
│ │ │
│ InMemoryProductRepository (ConcurrentHashMap) │
└───────────────────────────────────────────────────────────────────────┘
▲
Spotless guards every file in the repo:
*.java · pom.xml · application.yml · *.md · .github/*.yml

The API is intentionally simple. The interesting part is the build:

developer machine                         CI (GitHub Actions)
───────────────── ───────────────────
edit code checkout
mvn spotless:apply ◀── fixes style mvn spotless:check ── fails fast on style
git push ── pre-push hook runs check mvn verify ── tests + check again

Project structure:

spring-boot-spotless-maven-code-formatting-demo/
├── .editorconfig
├── .gitattributes
├── .github/workflows/ci.yml
├── .mvn/jvm.config
├── config/license-header.txt
├── pom.xml
└── src/
├── main/java/com/boottech/spotlessdemo/
│ ├── SpotlessDemoApplication.java
│ ├── config/ClockConfig.java
│ ├── controller/ProductController.java
│ ├── domain/Product.java
│ ├── dto/CreateProductRequest.java
│ ├── dto/UpdateProductRequest.java
│ ├── dto/ProductResponse.java
│ ├── exception/GlobalExceptionHandler.java
│ ├── exception/ProductNotFoundException.java
│ ├── exception/DuplicateSkuException.java
│ ├── repository/ProductRepository.java
│ ├── repository/InMemoryProductRepository.java
│ └── service/ProductService.java
├── main/resources/application.yml
└── test/java/com/boottech/spotlessdemo/
├── controller/ProductControllerTest.java
└── service/ProductServiceTest.java

Implementation

Step 1: Create the Spring Boot 4 project

Start with a standard Spring Boot 4 pom.xml. Spring Boot 4 split the web starter into modules, so we use spring-boot-starter-webmvc and its matching test starter.

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.1.2</version>
<relativePath/>
</parent>

<groupId>com.boottech</groupId>
<artifactId>spring-boot-spotless-maven-code-formatting-demo</artifactId>
<version>1.0.0-SNAPSHOT</version>

<properties>
<java.version>25</java.version>
<palantir-java-format.version>2.103.0</palantir-java-format.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spotless.version>3.11.0</spotless.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

Pin both the plugin version and the formatter version as properties. If you leave the formatter version out, Spotless uses its own default, and upgrading the plugin silently changes your formatting. That produces a “reformat everything” commit nobody planned.

Step 2: Pick a Java formatter

This is the only real decision in the whole setup. The main options:

We use palantir-java-format. Spring code is full of builders, streams and MockMvc chains. With google-java-format’s 100-column limit and 2-space indent these wrap aggressively. Palantir keeps 4-space indentation and 120 columns, which is close to what most Spring teams already write. Its lack of options is a feature: there is nothing left to argue about.

Choose Eclipse JDT only if you have a style document you are contractually stuck with. Every option you can configure is an option someone will want to change.

Step 3: Add the Spotless plugin with a Java format

<plugin>
<groupId>com.diffplug.spotless</groupId>
<artifactId>spotless-maven-plugin</artifactId>
<version>${spotless.version}</version>
<configuration>
<java>
<!-- Allows `// spotless:off` / `// spotless:on` around hand-aligned code -->
<toggleOffOn/>
<palantirJavaFormat>
<version>${palantir-java-format.version}</version>
<style>PALANTIR</style>
<formatJavadoc>true</formatJavadoc>
</palantirJavaFormat>
<importOrder>
<order>java|javax,jakarta,org,,com.boottech,\#</order>
</importOrder>
<removeUnusedImports/>
<forbidWildcardImports/>
<forbidModuleImports/>
<formatAnnotations/>
<licenseHeader>
<file>${project.basedir}/config/license-header.txt</file>
</licenseHeader>
</java>
</configuration>
</plugin>

Each step, in order:

  • toggleOffOn lets you protect a block with // spotless:off and // spotless:on. Use it for hand-aligned lookup tables or ASCII diagrams in comments, not to opt out of rules you dislike.
  • palantirJavaFormat does the heavy lifting: indentation, wrapping, braces, blank lines.
  • importOrder defines import groups. The syntax is a comma-separated list of prefixes:java|javax puts both prefixes in one group with no blank line between them, jakarta gets its own group, which keeps Bean Validation and Servlet imports visible, org collects Spring, JUnit, AssertJ, the empty entry ,, means “everything not matched elsewhere”, com.boottech keeps our own packages last among regular imports, \# is static imports, placed at the bottom
  • removeUnusedImports deletes dead imports. It uses google-java-format’s parser by default.
  • forbidWildcardImports is a lint: it cannot fix import org.foo.*; by itself, so it fails the build. Wildcards hide where a type comes from and cause compile errors when a new version of a library adds a class with a clashing name.
  • forbidModuleImports is new for Java 25. JEP 511 made import module java.base; final in Java 25. It is handy in scripts, but in a Spring application it pulls hundreds of names into scope. This step rejects it.
  • formatAnnotations fixes type annotations such as @Nullable that some formatters push onto their own line. It must come after the formatter.
  • licenseHeader injects the header from a file and replaces $YEAR with the current year.

The header file:

/*
* Copyright (c) $YEAR BootTech Solutions.
* Licensed under the Apache License, Version 2.0.
*/

Step 4: Format pom.xml with sortPom

Merge conflicts in pom.xml are common because everyone appends dependencies at the bottom. Sorting them gives each dependency a deterministic position:

<pom>
<sortPom>
<nrOfIndentSpace>2</nrOfIndentSpace>
<expandEmptyElements>false</expandEmptyElements>
<spaceBeforeCloseEmptyElement>false</spaceBeforeCloseEmptyElement>
<sortDependencies>scope,groupId,artifactId</sortDependencies>
<sortProperties>true</sortProperties>
</sortPom>
</pom>

sortDependencies groups compile-scope dependencies first, then test, each sorted alphabetically. expandEmptyElements=false keeps <relativePath/> as-is instead of turning it into <relativePath></relativePath>.

Tradeoff: sortPom also reorders top-level elements using its default sort order. On a large, hand-organized POM with comments between sections, the first run can be noisy. Run it once, review the diff, and commit it on its own.

Step 5: Cover YAML, Markdown and dotfiles

Java is not the only thing reviewers complain about. Trailing whitespace in application.yml and missing final newlines create useless diff lines too. A generic <format> handles them:

<formats>
<format>
<includes>
<include>src/**/*.yml</include>
<include>src/**/*.yaml</include>
<include>src/**/*.properties</include>
<include>.github/**/*.yml</include>
<include>*.md</include>
<include>.gitattributes</include>
<include>.gitignore</include>
<include>.editorconfig</include>
</includes>
<trimTrailingWhitespace/>
<endWithNewline/>
<indent>
<spaces>true</spaces>
<spacesPerTab>2</spacesPerTab>
</indent>
</format>
</formats>

Spotless also has a dedicated <yaml> format backed by Jackson. Do not use it on Spring configuration files. Jackson parses the YAML into a tree and prints it back, which drops every comment. Comments in application.yml often explain why a timeout is set to a strange value, so losing them hurts. The generic whitespace steps are safer.

The same caution applies to <markdown><flexmark/></markdown>: it reflows Markdown, which is fine for docs folders but can rewrite tables in a README that people edit by hand. Start with whitespace rules and tighten later.

Step 6: Enable incremental checking

<configuration>
<upToDateChecking>
<enabled>true</enabled>
</upToDateChecking>
...
</configuration>

Spotless keeps an index in target/spotless-index with each file’s path and last-modified timestamp, and skips files that have not changed since the last successful run. This has been on by default since plugin 2.35.0. Setting it explicitly documents the behavior and gives you one place to turn it off if the cache ever causes trouble. You can see it working in the logs:

[INFO] Spotless.Java is keeping 15 files clean - 0 needs changes to be clean, 0 were already clean, 15 were skipped because caching determined they were already clean

mvn clean deletes the index, so the next run checks everything again.

Step 7: Bind check to the build

<executions>
<execution>
<id>spotless-check</id>
<goals>
<goal>check</goal>
</goals>
<!-- bound to `verify` by default: `mvn verify` (CI) fails on unformatted code -->
</execution>
</executions>

spotless:check binds to the verify phase by default. That placement is deliberate:

  • mvn spring-boot:run, mvn test and IDE builds never reach verify, so formatting does not interrupt you while you experiment.
  • mvn verify and mvn install, which CI runs, fail on unformatted code.

You can bind it to an earlier phase with <phase>validate</phase> to fail before compilation. That gives faster feedback in CI, but every mvn test during local work will then fail on a stray space. Most teams find that annoying within a week. A better way to get fast feedback is to run spotless:check as its own CI step (Step 10).

Step 8: Run it on real code

Here is the controller as it was first written: mixed tabs and spaces, wildcard imports, a stray trailing space, and a one-line constructor.

package com.boottech.spotlessdemo.controller;
import org.springframework.web.bind.annotation.*;
import com.boottech.spotlessdemo.service.ProductService;
import java.util.List;
import java.util.UUID;
import java.util.Map;
import com.boottech.spotlessdemo.dto.*;
import org.springframework.http.ResponseEntity;
import jakarta.validation.Valid;
import java.net.URI;
@RestController
@RequestMapping("/api/v1/products")
public class ProductController
{
private final ProductService productService;
public ProductController(ProductService productService) { this.productService = productService; }

@PostMapping
public ResponseEntity<ProductResponse> create(@Valid @RequestBody CreateProductRequest request){
ProductResponse created=productService.create(request);
return ResponseEntity.created(URI.create("/api/v1/products/"+created.id())).body(created);
}

@GetMapping("/{id}")
public ProductResponse findById(@PathVariable UUID id) { return productService.findById(id); }

@GetMapping
public List<ProductResponse> findAll(@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "20") int size) {
return productService.findAll(page,size);
}
// ... update and delete omitted
}

First, see what is wrong without touching anything:

mvn spotless:check

Spotless prints a diff per file (dots represent spaces, so whitespace problems are visible) and ends with:

[ERROR]     src/main/java/com/boottech/spotlessdemo/SpotlessDemoApplication.java
[ERROR] @@ -1,3 +1,7 @@
[ERROR] +/*
[ERROR] +·*·Copyright·(c)·2026·BootTech·Solutions.
[ERROR] +·*·Licensed·under·the·Apache·License,·Version·2.0.
[ERROR] +·*/
[ERROR] package·com.boottech.spotlessdemo;
[ERROR] Violations also present in 11 other files.
[ERROR] Run 'mvn spotless:apply' to fix these violations.

Now fix it:

mvn spotless:apply

Spotless reformats every file it can, and then stops on what it cannot fix:

[ERROR] There were 2 lint error(s), they must be fixed or suppressed.
[ERROR] src/main/java/com/boottech/spotlessdemo/controller/ProductController.java:L13 toggle(import org.springframework.web.bind.annotation.*;) Do not use wildcard imports (e.g. java.util.*) - replace with specific class imports (e.g. java.util.List) as 'spotlessApply' cannot auto-fix this
[ERROR] src/main/java/com/boottech/spotlessdemo/controller/ProductController.java:L15 toggle(import com.boottech.spotlessdemo.dto.*;) Do not use wildcard imports (e.g. java.util.*) - replace with specific class imports (e.g. java.util.List) as 'spotlessApply' cannot auto-fix this

This is the difference between a formatter step (fixes the code) and a lint step (reports the problem). Replace the wildcards with explicit imports (IntelliJ’s “Optimize Imports” does it in one keystroke), run apply again, and you get:

/*
* Copyright (c) 2026 BootTech Solutions.
* Licensed under the Apache License, Version 2.0.
*/
package com.boottech.spotlessdemo.controller;

import java.net.URI;
import java.util.List;
import java.util.UUID;

import jakarta.validation.Valid;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.boottech.spotlessdemo.dto.CreateProductRequest;
import com.boottech.spotlessdemo.dto.ProductResponse;
import com.boottech.spotlessdemo.dto.UpdateProductRequest;
import com.boottech.spotlessdemo.service.ProductService;

@RestController
@RequestMapping("/api/v1/products")
public class ProductController {
private final ProductService productService;

public ProductController(ProductService productService) {
this.productService = productService;
}

@PostMapping
public ResponseEntity<ProductResponse> create(@Valid @RequestBody CreateProductRequest request) {
ProductResponse created = productService.create(request);
return ResponseEntity.created(URI.create("/api/v1/products/" + created.id()))
.body(created);
}

@GetMapping("/{id}")
public ProductResponse findById(@PathVariable UUID id) {
return productService.findById(id);
}

@GetMapping
public List<ProductResponse> findAll(
@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "20") int size) {
return productService.findAll(page, size);
}

@PutMapping("/{id}")
public ProductResponse update(@PathVariable UUID id, @Valid @RequestBody UpdateProductRequest request) {
return productService.update(id, request);
}

@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable UUID id) {
productService.delete(id);
return ResponseEntity.noContent().build();
}
}

What changed: license header added, unused java.util.Map removed, imports grouped as configured, tabs replaced, braces normalized, long parameter lists wrapped at 120 columns.

If a lint is legitimate in one place (generated code, a legacy package you are not allowed to touch), suppress it narrowly instead of disabling the step:

<lintSuppressions>
<lintSuppression>
<path>src/main/java/com/boottech/legacy/*</path>
<step>forbidWildcardImports</step>
<shortCode>*</shortCode>
</lintSuppression>
</lintSuppressions>

Step 9: The rest of the application

The remaining classes are ordinary Spring Boot code. Shown here after formatting, without the license header for brevity.

Entry point:

package com.boottech.spotlessdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpotlessDemoApplication {

public static void main(String[] args) {
SpringApplication.run(SpotlessDemoApplication.class, args);
}
}

Domain:

package com.boottech.spotlessdemo.domain;

import java.math.BigDecimal;
import java.time.Instant;
import java.util.Objects;
import java.util.UUID;

/** Immutable catalog product. */
public record Product(UUID id, String sku, String name, BigDecimal price, int stock, Instant createdAt) {

public Product {
Objects.requireNonNull(id, "id must not be null");
Objects.requireNonNull(sku, "sku must not be null");
Objects.requireNonNull(name, "name must not be null");
Objects.requireNonNull(price, "price must not be null");
Objects.requireNonNull(createdAt, "createdAt must not be null");
if (price.signum() < 0) {
throw new IllegalArgumentException("price must be positive or zero");
}
if (stock < 0) {
throw new IllegalArgumentException("stock must be positive or zero");
}
}

public Product withDetails(String newName, BigDecimal newPrice, int newStock) {
return new Product(id, sku, newName, newPrice, newStock, createdAt);
}
}

DTOs with Bean Validation. Two formatter decisions are visible here: formatAnnotations keeps the constraint annotations on the same line as each record component, and palantir-java-format puts a blank line between components that carry annotations. You might not choose that layout yourself, but nobody has to discuss it again:

package com.boottech.spotlessdemo.dto;

import java.math.BigDecimal;

import jakarta.validation.constraints.DecimalMin;
import jakarta.validation.constraints.Digits;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.PositiveOrZero;
import jakarta.validation.constraints.Size;

public record CreateProductRequest(
@NotBlank @Pattern(regexp = "^[A-Z]{3}-\\d{4}$", message = "must match AAA-0000") String sku,

@NotBlank @Size(max = 120) String name,

@NotNull @DecimalMin("0.00") @Digits(integer = 8, fraction = 2) BigDecimal price,

@PositiveOrZero int stock) {}-\\d{4}$", message = "must match AAA-0000") String sku,
@NotBlank @Size(max = 120) String name,
@NotNull @DecimalMin("0.00") @Digits(integer = 8, fraction = 2) BigDecimal price,
@PositiveOrZero int stock) {}
package com.boottech.spotlessdemo.dto;

import java.math.BigDecimal;

import jakarta.validation.constraints.DecimalMin;
import jakarta.validation.constraints.Digits;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.PositiveOrZero;
import jakarta.validation.constraints.Size;

public record UpdateProductRequest(
@NotBlank @Size(max = 120) String name,

@NotNull @DecimalMin("0.00") @Digits(integer = 8, fraction = 2) BigDecimal price,

@PositiveOrZero int stock) {}
package com.boottech.spotlessdemo.dto;

import java.math.BigDecimal;
import java.time.Instant;
import java.util.UUID;

import com.boottech.spotlessdemo.domain.Product;

public record ProductResponse(UUID id, String sku, String name, BigDecimal price, int stock, Instant createdAt) {

public static ProductResponse from(Product product) {
return new ProductResponse(
product.id(), product.sku(), product.name(), product.price(), product.stock(), product.createdAt());
}
}

Repository. A thread-safe in-memory store keeps the focus on formatting rather than persistence:

package com.boottech.spotlessdemo.repository;

import java.util.List;
import java.util.Optional;
import java.util.UUID;

import com.boottech.spotlessdemo.domain.Product;

public interface ProductRepository {

Product save(Product product);

Optional<Product> findById(UUID id);

Optional<Product> findBySku(String sku);

List<Product> findAll(int page, int size);

boolean deleteById(UUID id);
}
package com.boottech.spotlessdemo.repository;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.stereotype.Repository;

import com.boottech.spotlessdemo.domain.Product;

/** Thread-safe in-memory store. Keeps the demo focused on formatting rather than persistence. */
@Repository
public class InMemoryProductRepository implements ProductRepository {

private final Map<UUID, Product> store = new ConcurrentHashMap<>();

@Override
public Product save(Product product) {
store.put(product.id(), product);
return product;
}

@Override
public Optional<Product> findById(UUID id) {
return Optional.ofNullable(store.get(id));
}

@Override
public Optional<Product> findBySku(String sku) {
return store.values().stream().filter(p -> p.sku().equals(sku)).findFirst();
}

@Override
public List<Product> findAll(int page, int size) {
return store.values().stream()
.sorted(Comparator.comparing(Product::createdAt).thenComparing(Product::sku))
.skip((long) page * size)
.limit(size)
.toList();
}

@Override
public boolean deleteById(UUID id) {
return store.remove(id) != null;
}
}

Service. It uses Math.clamp (Java 21+) to bound page size and an injected Clock for testable timestamps:

package com.boottech.spotlessdemo.service;

import java.time.Clock;
import java.time.Instant;
import java.util.List;
import java.util.UUID;

import org.springframework.stereotype.Service;

import com.boottech.spotlessdemo.domain.Product;
import com.boottech.spotlessdemo.dto.CreateProductRequest;
import com.boottech.spotlessdemo.dto.ProductResponse;
import com.boottech.spotlessdemo.dto.UpdateProductRequest;
import com.boottech.spotlessdemo.exception.DuplicateSkuException;
import com.boottech.spotlessdemo.exception.ProductNotFoundException;
import com.boottech.spotlessdemo.repository.ProductRepository;

@Service
public class ProductService {

private static final int MAX_PAGE_SIZE = 100;

private final ProductRepository repository;
private final Clock clock;

public ProductService(ProductRepository repository, Clock clock) {
this.repository = repository;
this.clock = clock;
}

public ProductResponse create(CreateProductRequest request) {
repository.findBySku(request.sku()).ifPresent(existing -> {
throw new DuplicateSkuException(request.sku());
});
Product product = new Product(
UUID.randomUUID(), request.sku(), request.name(), request.price(), request.stock(), Instant.now(clock));
return ProductResponse.from(repository.save(product));
}

public ProductResponse findById(UUID id) {
return repository.findById(id).map(ProductResponse::from).orElseThrow(() -> new ProductNotFoundException(id));
}

public List<ProductResponse> findAll(int page, int size) {
int safePage = Math.max(page, 0);
int safeSize = Math.clamp(size, 1, MAX_PAGE_SIZE);
return repository.findAll(safePage, safeSize).stream()
.map(ProductResponse::from)
.toList();
}

public ProductResponse update(UUID id, UpdateProductRequest request) {
Product current = repository.findById(id).orElseThrow(() -> new ProductNotFoundException(id));
Product updated = current.withDetails(request.name(), request.price(), request.stock());
return ProductResponse.from(repository.save(updated));
}

public void delete(UUID id) {
if (!repository.deleteById(id)) {
throw new ProductNotFoundException(id);
}
}
}

The check-then-save in create is not atomic. Two concurrent requests with the same SKU can both pass. With a real database, enforce uniqueness with a unique constraint on sku and translate the constraint violation into DuplicateSkuException.

package com.boottech.spotlessdemo.config;

import java.time.Clock;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration(proxyBeanMethods = false)
public class ClockConfig {

@Bean
Clock clock() {
return Clock.systemUTC();
}
}

Error handling with RFC 9457 ProblemDetail:

package com.boottech.spotlessdemo.exception;

import java.net.URI;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(ProductNotFoundException.class)
ProblemDetail handleNotFound(ProductNotFoundException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
problem.setType(URI.create("https://api.boottech.dev/problems/product-not-found"));
problem.setTitle("Product not found");
return problem;
}

@ExceptionHandler(DuplicateSkuException.class)
ProblemDetail handleDuplicate(DuplicateSkuException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, ex.getMessage());
problem.setType(URI.create("https://api.boottech.dev/problems/duplicate-sku"));
problem.setTitle("Duplicate SKU");
return problem;
}

@ExceptionHandler(MethodArgumentNotValidException.class)
ProblemDetail handleValidation(MethodArgumentNotValidException ex) {
Map<String, String> errors = ex.getBindingResult().getFieldErrors().stream()
.collect(Collectors.toMap(
FieldError::getField,
error -> error.getDefaultMessage() == null ? "invalid" : error.getDefaultMessage(),
(first, second) -> first));
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Request validation failed");
problem.setType(URI.create("https://api.boottech.dev/problems/validation"));
problem.setTitle("Invalid request");
problem.setProperty("errors", errors);
return problem;
}
}
package com.boottech.spotlessdemo.exception;

import java.util.UUID;

public class ProductNotFoundException extends RuntimeException {

public ProductNotFoundException(UUID id) {
super("Product %s not found".formatted(id));
}
}
package com.boottech.spotlessdemo.exception;

public class DuplicateSkuException extends RuntimeException {

public DuplicateSkuException(String sku) {
super("A product with SKU %s already exists".formatted(sku));
}
}

Do not also set spring.mvc.problemdetails.enabled=true here. That property registers Spring Boot’s own ResponseEntityExceptionHandler, which handles MethodArgumentNotValidException before your advice does, and your errors map disappears from the response. We hit this while building the demo.

application.yml:

spring:
application:
name: spotless-demo

server:
port: 8080

management:
endpoints:
web:
exposure:
include: health,info

Step 10: Enforce it in CI

.github/workflows/ci.yml:

name: ci

on:
push:
branches: [main]
pull_request:

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # full history so the spotless-ratchet profile can resolve origin/main

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

- name: Check formatting (fast fail)
run: mvn -B -ntp spotless:check

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

The separate spotless:check step fails in seconds, before compilation and tests, and shows a clear “formatting” failure in the PR checks. The second check inside verify costs almost nothing because the index from the first run skips every file.

Locally, install the pre-push hook so problems never reach CI:

mvn spotless:install-git-pre-push-hook

When you push, the hook runs spotless:check. If it fails, the hook runs spotless:apply, aborts the push, and asks you to commit the fixes. It is a pre-push hook, not pre-commit, so your local commit history can still contain unformatted work in progress.

Step 11: Align the IDE

Spotless is the source of truth, but you do not want your IDE to fight it on every save. Add an .editorconfig that matches the formatter:

root = true

[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
indent_style = space

[*.java]
indent_size = 4
max_line_length = 120

[*.{xml,yml,yaml,json,md}]
indent_size = 2

For IntelliJ, install the palantir-java-format plugin so “Reformat Code” produces the same output as Spotless. Otherwise, run mvn spotless:apply before committing, or set up a file watcher on it.

Line endings are configured through .gitattributes:

* text=auto eol=lf
*.cmd text eol=crlf
*.bat text eol=crlf
*.jar binary

Spotless’s default lineEndings mode, GIT_ATTRIBUTES_FAST_ALLSAME, reads this file. Do not override it in the plugin. If Spotless and Git disagree on line endings, Windows developers get a check that fails on files that look identical.

Step 12: Adopting Spotless on an existing codebase

On a new project, run spotless:apply once and you are done. On a 2,000-file legacy service, a single “format everything” commit has real costs:

  • it conflicts with every open branch
  • git blame points to the formatting commit instead of the real author

You have two good options.

Option A: one big commit, hidden from blame. Format everything in one commit, then add its hash to .git-blame-ignore-revs:

mvn spotless:apply
git commit -am "style: apply spotless formatting"
git rev-parse HEAD >> .git-blame-ignore-revs
git config blame.ignoreRevsFile .git-blame-ignore-revs

GitHub honors .git-blame-ignore-revs automatically in its blame view. Merge this right after a release, when few branches are open.

Option B: ratchet. Only enforce formatting on files changed since a reference:

<profiles>
<profile>
<id>spotless-ratchet</id>
<build>
<plugins>
<plugin>
<groupId>com.diffplug.spotless</groupId>
<artifactId>spotless-maven-plugin</artifactId>
<configuration>
<ratchetFrom>origin/main</ratchetFrom>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
mvn -Pspotless-ratchet spotless:check

Files you touch get formatted, and untouched files stay as they are. The codebase converges over a few months. Always ratchet from a remote ref like origin/main or a tag, never from HEAD: with HEAD, whatever you just committed becomes the baseline, even if it was badly formatted.

Ratchet mode has one CI catch. GitHub Actions checks out a shallow clone by default, so origin/main does not exist and Spotless fails with No such reference. That is why the workflow uses fetch-depth: 0. A cheaper alternative is a git fetch origin main step before the check.

Testing

Formatting has two kinds of “tests”: the Spotless check itself, and making sure formatting never changed behavior.

The check as a test

mvn spotless:check

A passing run prints, per format:

[INFO] Spotless.Format is keeping 5 files clean - 0 needs changes to be clean, ...
[INFO] Spotless.Java is keeping 15 files clean - 0 needs changes to be clean, ...
[INFO] Spotless.Pom is keeping 1 files clean - 0 needs changes to be clean, ...

Behavior tests

Formatters only change whitespace and imports. A broken step, or a refactoring step like Cleanthat, could still change behavior, so keep a normal test suite running in the same mvn verify.

Service unit test with a fixed clock:

package com.boottech.spotlessdemo.service;

import java.math.BigDecimal;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.UUID;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import com.boottech.spotlessdemo.dto.CreateProductRequest;
import com.boottech.spotlessdemo.dto.ProductResponse;
import com.boottech.spotlessdemo.dto.UpdateProductRequest;
import com.boottech.spotlessdemo.exception.DuplicateSkuException;
import com.boottech.spotlessdemo.exception.ProductNotFoundException;
import com.boottech.spotlessdemo.repository.InMemoryProductRepository;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

class ProductServiceTest {

private static final Instant NOW = Instant.parse("2026-11-03T10:15:30Z");

private ProductService service;

@BeforeEach
void setUp() {
service = new ProductService(new InMemoryProductRepository(), Clock.fixed(NOW, ZoneOffset.UTC));
}

@Test
void createsProductWithServerSideTimestamp() {
ProductResponse created = service.create(keyboard());

assertThat(created.id()).isNotNull();
assertThat(created.sku()).isEqualTo("KEY-0001");
assertThat(created.createdAt()).isEqualTo(NOW);
}

@Test
void rejectsDuplicateSku() {
service.create(keyboard());

assertThatThrownBy(() -> service.create(keyboard()))
.isInstanceOf(DuplicateSkuException.class)
.hasMessageContaining("KEY-0001");
}

@Test
void updatesNamePriceAndStockButKeepsSku() {
ProductResponse created = service.create(keyboard());

ProductResponse updated = service.update(
created.id(), new UpdateProductRequest("Mechanical Keyboard v2", new BigDecimal("99.90"), 5));

assertThat(updated.sku()).isEqualTo("KEY-0001");
assertThat(updated.name()).isEqualTo("Mechanical Keyboard v2");
assertThat(updated.price()).isEqualByComparingTo("99.90");
assertThat(updated.stock()).isEqualTo(5);
}

@Test
void clampsPageSizeToUpperBound() {
for (int i = 0; i < 120; i++) {
service.create(new CreateProductRequest("SKU-%04d".formatted(i), "Item " + i, BigDecimal.ONE, 1));
}

assertThat(service.findAll(0, 1_000)).hasSize(100);
assertThat(service.findAll(-3, 0)).hasSize(1);
}

@Test
void deletingUnknownProductFails() {
UUID unknown = UUID.randomUUID();

assertThatThrownBy(() -> service.delete(unknown)).isInstanceOf(ProductNotFoundException.class);
}

private static CreateProductRequest keyboard() {
return new CreateProductRequest("KEY-0001", "Mechanical Keyboard", new BigDecimal("129.00"), 10);
}
}

Web layer test with Spring Framework 7’s AssertJ-based MockMvcTester. Note that in Spring Boot 4, @AutoConfigureMockMvc lives in org.springframework.boot.webmvc.test.autoconfigure:

package com.boottech.spotlessdemo.controller;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.assertj.MockMvcTester;

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest
@AutoConfigureMockMvc
class ProductControllerTest {

@Autowired
private MockMvcTester mvc;

@Test
void createThenFetchProduct() {
var created = mvc.post()
.uri("/api/v1/products")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{"sku":"MOU-0042","name":"Wireless Mouse","price":39.90,"stock":25}
""")
.exchange();

assertThat(created).hasStatus(HttpStatus.CREATED);
assertThat(created).headers().containsHeader("Location");
assertThat(created).bodyJson().extractingPath("$.sku").isEqualTo("MOU-0042");

String location = created.getResponse().getHeader("Location");
assertThat(mvc.get().uri(location))
.hasStatusOk()
.bodyJson()
.extractingPath("$.name")
.isEqualTo("Wireless Mouse");
}

@Test
void invalidPayloadReturnsProblemDetailWithFieldErrors() {
assertThat(mvc.post()
.uri("/api/v1/products")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{"sku":"bad","name":"","price":-1,"stock":-5}
"""))
.hasStatus(HttpStatus.BAD_REQUEST)
.bodyJson()
.extractingPath("$.errors")
.asMap()
.containsKeys("sku", "name", "price", "stock");
}

@Test
void unknownProductReturns404() {
assertThat(mvc.get().uri("/api/v1/products/{id}", "3f2c8a5e-0000-4000-8000-000000000000"))
.hasStatus(HttpStatus.NOT_FOUND)
.bodyJson()
.extractingPath("$.title")
.isEqualTo("Product not found");
}
}

Look at how palantir-java-format wraps the assertThat(...) chains: one call per line, aligned at 8 spaces. That consistency is what makes test diffs readable.

Full run:

mvn verify
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0 -- in com.boottech.spotlessdemo.service.ProductServiceTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0 -- in com.boottech.spotlessdemo.controller.ProductControllerTest
[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0
[INFO] --- spotless:3.11.0:check (spotless-check) @ spring-boot-spotless-maven-code-formatting-demo ---
[INFO] BUILD SUCCESS

Manual API check:

mvn spring-boot:run

curl -i -X POST localhost:8080/api/v1/products \
-H 'Content-Type: application/json' \
-d '{"sku":"KEY-0001","name":"Mechanical Keyboard","price":129.00,"stock":10}'
# HTTP/1.1 201
# Location: /api/v1/products/<uuid>

curl -i -X POST localhost:8080/api/v1/products \
-H 'Content-Type: application/json' \
-d '{"sku":"KEY-0001","name":"Duplicate","price":1,"stock":1}'
# HTTP/1.1 409 {"title":"Duplicate SKU", ...}

Performance Considerations

On the demo (15 Java files, 1 POM, 5 other files) on a laptop, mvn -q spotless:check:

Most of that is Maven and JVM startup plus loading the formatter, not formatting. The index matters more as the codebase grows: on large modules, warm runs only touch files you changed.

Some things to keep in mind as you scale:

  • Formatter artifacts are downloaded on first use (palantir-java-format, sortpom). Cache ~/.m2 in CI (cache: maven in setup-java), or the first run of every job pays for the download.
  • Multi-module builds: declare the plugin in the parent’s <pluginManagement> and <plugins>, so every module inherits the same configuration. Each module keeps its own index in its own target/.
  • expandWildcardImports is expensive: it resolves the full classpath with JavaParser. Use it once to clean up a legacy codebase, then switch to forbidWildcardImports.
  • Formatting one file: mvn spotless:apply -DspotlessFiles=.*ProductController.java is useful in editor file watchers. The value is a regex matched against the absolute path.
  • Many repositories: publish the formatter configuration as a Maven artifact (a jar containing license-header.txt, import order, Eclipse XML) and add it as a plugin <dependency>. Spotless resolves configuration files from the plugin classpath, so 30 services can share one style without copy-paste.

Common Pitfalls

1. Not pinning the formatter version. Plugin upgrade → new default formatter → hundreds of files flagged on an unrelated PR. Pin <version> inside <palantirJavaFormat> and upgrade it on purpose, in its own PR, followed by spotless:apply.

2. JDK 25 sun.misc.Unsafe warning. On Java 25 you will see:

WARNING: A terminally deprecated method in sun.misc.Unsafe has been called
WARNING: sun.misc.Unsafe::staticFieldBase has been called by com.diffplug.spotless.java.ModuleHelper

It is a warning, not a failure. Spotless uses this API to open JDK compiler internals for the formatter. To keep build logs clean, add a .mvn/jvm.config file:

--sun-misc-unsafe-memory-access=allow

Revisit this when a future JDK removes the API. At that point you will need a Spotless release that no longer uses it.

3. Formatting YAML with Jackson. As covered in Step 5, <yaml><jackson/></yaml> removes comments. Use generic steps for Spring config files.

4. Shallow clones with ratchetFrom. No such reference 'origin/main' in CI means the ref was not fetched. Use fetch-depth: 0 or git fetch origin main.

5. Abusing spotless:off. When half the files contain // spotless:off, you no longer have a style. Allow it in code review only with a comment explaining why.

6. Skipping the check “temporarily”. -Dspotless.check.skip=true exists, and so do spotless.apply.skip and spotless.skip. If it ends up in a CI script, nobody will remove it. If formatting blocks a hotfix, run spotless:apply: it takes seconds.

7. Generated sources. Spotless only targets src/main/java and src/test/java by default, so code generated into target/generated-sources (OpenAPI, MapStruct, jOOQ) is ignored, which is what you want. If your generator writes into src/, add an <excludes> entry rather than formatting generated code.

8. Step order conflicts. formatAnnotations placed before the formatter does nothing, since the formatter undoes it. When in doubt, follow the order in the official README: refactoring (Cleanthat) → formatter → import tweaks → annotation fixes → license header.

Alternative Approaches

The common production setup is Spotless for formatting + Checkstyle or Error Prone for semantics. Let Spotless own whitespace and imports, disable every whitespace rule in Checkstyle, and let Checkstyle focus on what a formatter cannot fix.

Spotless is the wrong choice when your organization already mandates a different enforced formatter, or when your build cannot download artifacts at runtime and you have no internal mirror for the formatter jars.

Key Takeaways

  • Spotless moves formatting from code review into the build: apply locally, check in CI, and pin the formatter version so upgrades are deliberate.
  • Format more than Java. sortPom, license headers and whitespace rules on YAML and Markdown remove most noise from diffs, but avoid comment-dropping YAML formatters on Spring config.
  • On existing codebases, choose between one big commit plus .git-blame-ignore-revs, or a ratchet from origin/main, and remember the shallow clone trap in CI.

The complete source code is available on GitHub.

Support me through GitHub Sponsors.

Thank you for Reading !! See you in the next post.

References

👉 Link to Medium blog

Related Posts