Spotless is a popular tool that can format code in any programming language out there (Java, JavaScript, Python, C#, TypeScript, etc.) using any build tools. (Gradle, Maven, etc.)
In this tutorial we will look into integrating it in a Java project built with Gradle. In order to do this, we just need to add and configure Spotless in the build.gradle file in 3 easy steps:
1. Add the Spotless plugin:
plugins {
id "com.diffplug.spotless" version "6.19.0"
}
2. Configure the formatting jobs:
spotless {
java {
googleJavaFormat() // format the code in Google Java format
importOrder() // order the imports
removeUnusedImports() // remove the unused imports
formatAnnotations() // format the annotations
}
}
3. Trigger Spotless automatically when the project is compiled:
tasks.withType(SourceTask) {
finalizedBy 'spotlessApply'
}
Worth mentioning is that Spotless also offers additional features like automatic refactoring of the Java code using cleanthat().