How to Integrate Spotless in Java Projects
Spotless is a code-formatting tool for Java projects that automatically formats source code according to predefined coding standards. It helps maintain consistent code formatting across a development team and can be integrated with Maven, Gradle, Jenkins, GitHub Actions, and other CI/CD tools.
GitHub Repository: Spotless - GitHub
1. Why Use Spotless?
Spotless helps you maintain consistent code formatting across Java projects.
- Automatically format Java source code.
- Maintain consistent coding standards.
- Remove unwanted import statements.
- Format code using Google Java Format.
- Validate formatting before committing code.
- Fail CI/CD pipelines when formatting rules are violated.
- Apply the same formatting rules across the development team.
2. Spotless Architecture
Spotless follows a simple code-formatting workflow:
- Developer writes Java source code.
- Spotless plugin reads the configured formatting rules.
- Spotless applies formatting or validates the source code.
- Formatted code is accepted, or validation fails if formatting rules are violated.
3. Integrate Spotless with Gradle
If your Java project uses Gradle, follow these steps.
Step 1: Add the Spotless Plugin
Open your build.gradle file and add:
plugins {
id 'java'
id 'com.diffplug.spotless' version '<latest-stable-version>'
}
Replace the placeholder with the current stable version from Gradle Plugin Portal.
Step 2: Configure Java Formatting
Add the following configuration to build.gradle:
spotless {
java {
// Format Java code using Google Java Format
googleJavaFormat()
// Remove unused imports
removeUnusedImports()
// Sort imports
importOrder('java', 'javax', 'org', 'com')
// Remove trailing whitespace
trimTrailingWhitespace()
// Ensure files end with a newline
endWithNewline()
// Include Java source files
target 'src/**/*.java'
}
}
Step 3: Execute Spotless Commands
| Command | Description |
|---|---|
gradle spotlessApply |
Automatically format Java files. |
gradle spotlessCheck |
Validate Java formatting. |
gradle build |
Build the project and run verification tasks. |
gradle check |
Run verification tasks, including Spotless checks. |
Linux / macOS
./gradlew spotlessApply
./gradlew spotlessCheck
./gradlew build
Windows
gradlew.bat spotlessApply
gradlew.bat spotlessCheck
gradlew.bat build
Step 4: Java Class Before Formatting
package org.example;
import java.util.*;
public class Main{
public static void main(String[] args){
List<String> names=Arrays.asList("Sumit","Rahul","Amit");
for(String name:names){
System.out.println(name);
}
}
}
After Formatting
Execute the following command:
./gradlew spotlessApply
Google Java Format will produce consistently formatted code:
package org.example;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> names = Arrays.asList("Sumit", "Rahul", "Amit");
for (String name : names) {
System.out.println(name);
}
}
}
4. Integrate Spotless with Maven
If your Java project uses Maven, integrate Spotless through pom.xml.
Step 1: Add the Maven Plugin
Add this configuration inside your Maven project:
<properties>
<spotless.version>REPLACE_WITH_LATEST_VERSION</spotless.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>com.diffplug.spotless</groupId>
<artifactId>spotless-maven-plugin</artifactId>
<version>${spotless.version}</version>
<configuration>
<java>
<googleJavaFormat/>
<removeUnusedImports/>
<importOrder>
<order>java,javax,org,com</order>
</importOrder>
</java>
</configuration>
<executions>
<execution>
<goals>
<goal>check</goal>
</goals>
<phase>verify</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
Use the current stable Maven plugin version from Maven Central.
Step 2: Execute Maven Commands
# Automatically format Java files
mvn spotless:apply
# Check Java formatting
mvn spotless:check
# Compile and run tests
mvn test
# Run formatting validation and verification
mvn verify
Because Spotless is configured to run during the Maven
verify phase, mvn verify
automatically checks formatting.
The spotless:check goal fails when source files
do not comply with configured formatting rules.
5. Spotless Formatting Options
Spotless supports multiple Java formatting engines and formatting steps.
| Formatter | Description |
|---|---|
googleJavaFormat() |
Google Java coding standards. |
palantirJavaFormat() |
Palantir Java formatting. |
eclipse() |
Eclipse Java formatter. |
removeUnusedImports() |
Removes unused imports. |
importOrder() |
Organizes imports. |
forbidWildcardImports() |
Prevents wildcard imports. |
formatAnnotations() |
Formats Java annotations. |
licenseHeader() |
Adds copyright and license headers. |
Official documentation:
6. Integrate Spotless with Jenkins CI/CD
You can run Spotless as part of your Jenkins pipeline to ensure that developers follow consistent Java formatting standards.
Example Jenkinsfile
pipeline {
agent any
stages {
stage('Checkout') {
steps {
checkout scm
}
}
stage('Check Code Formatting') {
steps {
sh './gradlew spotlessCheck'
}
}
stage('Compile') {
steps {
sh './gradlew compileJava'
}
}
stage('Run Tests') {
steps {
sh './gradlew test'
}
}
stage('Build') {
steps {
sh './gradlew build'
}
}
}
}
For Windows Jenkins agents, replace sh with
bat and use gradlew.bat.
7. Integrate Spotless with GitHub Actions
GitHub Actions can automatically validate Java formatting whenever developers push code or create pull requests.
Example .github/workflows/java.yml
name: Java CI with Spotless
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Java
uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '17'
- name: Check Formatting
run: ./gradlew spotlessCheck
- name: Run Tests
run: ./gradlew test
- name: Build
run: ./gradlew build
8. Spotless vs Checkstyle vs SonarQube
| Feature | Spotless | Checkstyle | SonarQube |
|---|---|---|---|
| Code formatting | Yes | No | No |
| Coding standards | Yes | Yes | Yes |
| Automatic formatting | Yes | No | No |
| Unused imports | Yes | Limited | Yes |
| Code quality analysis | Limited | Limited | Yes |
| CI/CD integration | Yes | Yes | Yes |
| Code duplication | No | No | Yes |
Recommendation:
- Use Spotless for automatic code formatting.
- Use Checkstyle for coding-standard enforcement.
- Use SonarQube for code-quality analysis.
9. Recommended Project Workflow
- Developer writes Java code: Implement application logic and automated tests.
-
Run Spotless Apply:
Automatically format source code.
./gradlew spotlessApply - Commit code to Git: Push formatted code to GitHub.
-
CI/CD executes Spotless Check:
Validate formatting standards.
./gradlew spotlessCheck - Execute automated tests: Run JUnit, TestNG, Selenium, or API tests.
- Build and deploy: Continue only when the pipeline succeeds.
10. Important Prerequisites
- Spotless Maven plugin requires Java runtime 17 or newer.
- Spotless Gradle plugin requires Java runtime 17+ and Gradle 7.3 or newer, according to its documentation.
- Use Gradle Wrapper or Maven Wrapper to keep build environments consistent.
- Commit formatting configuration so the whole team uses the same rules.

No comments:
Post a Comment