Spring Cloud Build comes with a set of checkstyle rules. You can find them in the spring-cloud-build-tools module. The most notable files under the module are:
spring-cloud-build-tools/.
└── src ├── checkstyle │ └── checkstyle-suppressions.xml└── main └── resources ├── checkstyle-header.txt
├── checkstyle.xml
└── intellij ├── Intellij_Project_Defaults.xml
└── Intellij_Spring_Boot_Java_Conventions.xml
Default Checkstyle rules | |
File header setup | |
Default suppression rules | |
Project defaults for Intellij that apply most of Checkstyle rules | |
Project style conventions for Intellij that apply most of Checkstyle rules |
Checkstyle rules are disabled by default. To add checkstyle to your project just define the following properties and plugins.
pom.xml.
<properties> <maven-checkstyle-plugin.failsOnError>true</maven-checkstyle-plugin.failsOnError><maven-checkstyle-plugin.failsOnViolation>true </maven-checkstyle-plugin.failsOnViolation>
<maven-checkstyle-plugin.includeTestSourceDirectory>true </maven-checkstyle-plugin.includeTestSourceDirectory>
</properties> <build> <plugins> <plugin>
<groupId>io.spring.javaformat</groupId> <artifactId>spring-javaformat-maven-plugin</artifactId> </plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> </plugin> </plugins> </build> <reporting> <plugins> <plugin>
<groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> </plugin> </plugins> </reporting> </build>
Fails the build upon Checkstyle errors | |
Fails the build upon Checkstyle violations | |
Checkstyle analyzes also the test sources | |
Add the Spring Java Format plugin that will reformat your code to pass most of the Checkstyle formatting rules | |
Add checkstyle plugin to your build and reporting phases |
If you need to suppress some rules (e.g. line length needs to be longer), then it’s enough for you to define a file under ${project.root}/src/checkstyle/checkstyle-suppressions.xml with your suppressions. Example:
projectRoot/src/checkstyle/checkstyle-suppresions.xml.
<?xml version="1.0"?> <!DOCTYPE suppressions PUBLIC "-//Puppy Crawl//DTD Suppressions 1.1//EN" "https://www.puppycrawl.com/dtds/suppressions_1_1.dtd"> <suppressions> <suppress files=".*ConfigServerApplication\.java" checks="HideUtilityClassConstructor"/> <suppress files=".*ConfigClientWatch\.java" checks="LineLengthCheck"/> </suppressions>
It’s advisable to copy the ${spring-cloud-build.rootFolder}/.editorconfig and ${spring-cloud-build.rootFolder}/.springformat to your project. That way, some default formatting rules will be applied.