介绍
- Spotless 是一个代码格式化工具。
- 它支持的开发语言有java, kotlin, scala, sql, javascript, css, json, yaml, etc。
- 它可以提示哪里不规范,同时也支持自动修正(其实就是批量的将所有类格式化)
- 支持maven|gradle plugin等插件
接入
下载 check code xml
intellij-java-google-style.xml
pom引入spotless 插件
<plugin>
<groupId>com.diffplug.spotless</groupId>
<artifactId>spotless-maven-plugin</artifactId>
<version>2.22.1</version>
<configuration>
<java>
<eclipse>
<file>${maven.multiModuleProjectDirectory}/src/resources/intellij-java-google-style.xml</file>
</eclipse>
<licenseHeader>
<file>${maven.multiModuleProjectDirectory}/src/resources/license-header</file>
</licenseHeader>
</java>
</configuration>
<!-- 将 Spotless apply 绑定到 compile 阶段,这样本地执行 mvn install 时就能自动格式化。-->
<executions>
<execution>
<goals>
<goal>apply</goal>
</goals>
<phase>compile</phase>
</execution>
</executions>
</plugin>
Spotless 支持格式化指定目录,以及排除指定目录的功能,详情参考spotless-maven-plugin。如无指定,执行 check 或 apply 时,默认项目全量代码。
检验
#格式化
mvn spotless:apply
# 检查
mvn spotless:check
开发过程中 格式化 文件
- 安装插件 Eclipse Code Formatter
- 选择
intellij-java-google-style.xml
为默认格式化模板 - 使用 IDEA 代码格式化快捷键,就可以完成 Spotless 代码格式化
问题
Spotless 与 Checkstyle 可能冲突,那要看取舍调整了