Spotless-Maven 格式化配置教程
Spotless 是一个代码格式化工具,可以帮助你保持代码风格的一致性。以下是配置 Spotless-Maven 插件的详细教程。
1. 基本配置
在项目的 pom.xml
文件中添加以下插件配置:
<build>
<plugins>
<plugin>
<groupId>com.diffplug.spotless</groupId>
<artifactId>spotless-maven-plugin</artifactId>
<version>2.37.0</version> <!-- 使用版本 -->
<configuration>
<!-- 通用配置 -->
<formats>
<!-- 格式化其他文件类型 -->
<format>
<includes>
<include>*.md</include>
<include>.gitignore</include>
</includes>
<trimTrailingWhitespace/>
<endWithNewline/>
<indent>
<spaces>true</spaces>
<spacesPerTab>4</spacesPerTab>
</indent>
</format>
</formats>
<!-- Java 代码格式化配置 -->
<java>
<!-- 使用 google-java-format -->
<googleJavaFormat>
<version>1.15.0</version>
<style>GOOGLE</style>
</googleJavaFormat>
<!-- 移除未使用的 imports -->
<removeUnusedImports/>
<!-- 许可证头 -->
<licenseHeader>
<content>/* Licensed under Apache-2.0 */</content>
</licenseHeader>
</java>
</configuration>
</plugin>
</plugins>
</build>
2. 常用命令
-
检查格式化问题:
mvn spotless:check
-
应用格式化:
mvn spotless:apply
-
在构建时自动检查 (推荐):
mvn clean install spotless:check
3. 高级配置
3.1 使用 Eclipse 格式化
如果你更喜欢 Eclipse 的代码风格:
<java>
<eclipse>
<version>4.21.0</version>
<file>${project.basedir}/eclipse-formatter.xml</file>
</eclipse>
<removeUnusedImports/>
</java>
你需要提供一个 Eclipse 格式化配置文件。
3.2 配置多个语言
<configuration>
<java>...</java>
<!-- Kotlin 格式化 -->
<kotlin>
<ktlint>
<version>0.45.2</version>
</ktlint>
</kotlin>
<!-- Scala 格式化 -->
<scala>
<scalafmt>
<version>3.5.9</version>
<config>
<version>3.5.9</version>
<style>default</style>
</config>
</scalafmt>
</scala>
</configuration>
3.3 跳过文件
<java>
<target>
<excludes>
<exclude>generated/**/*.java</exclude>
</excludes>
</target>
</java>
4. 与 IDE 集成
IntelliJ IDEA
- 安装
google-java-format
插件 - 配置插件使用与 Spotless 相同的版本
- 启用 "Reformat on save" 选项
Eclipse
- 安装 Eclipse Code Formatter 插件
- 导入与 Spotless 相同的格式化配置
5. 实践
- 在 CI/CD 流水线中添加
spotless:check
步骤 - 在 pre-commit hook 中添加格式化检查
- 团队统一格式化配置
- 对新项目从一开始就配置 Spotless
6. 常见问题
Q: 格式化后 git 显示大量更改怎么办?
A: 建议在项目开始时配置 Spotless,或者专门进行一次格式化提交。
Q: 如何自定义格式化规则?
A: 对于 Java,可以创建自定义的 Eclipse 格式化文件或调整 google-java-format 选项。
Q: 格式化性能如何?
A: Spotless 性能很好,但首次运行可能较慢,因为它需要下载格式化工具。
(本文来源:nzw6.com)