Checkstyle可以做到自定义风格的代码检查,这里提供一些使用的例子供参考。
使用checkstyle-IDEA插件,可以直接依靠idea检查代码,优点是有图形界面,操作直观,安装好之后所有项目共用,缺点是需要手动执行检查。
按快捷键 Ctrl+Alt+S ,选择Plugins ,在marketplace输入checkStyle-IDEA搜索安装。

如果搜索不到,也可以打开插件官网https://plugins.jetbrains.com/搜索checkStyle-IDEA,点击安装后,回到idea会自动下载安装。


安装好之后,按快捷键Ctrl+Alt+S,选择Checkstyle项进行配置,如图(检查规则文件可以参考文末我自定义的)

在左下角有Checkstyle的选项卡,选择规则文件运行即可。

由于项目是Maven项目,希望在编译的时候自动执行检查,不需要额外手动执行,可以选择在pom.xml配置maven-checkstyle-plugin插件,绑定到Maven的生命周期,这样在执行mvn compile等命令时自动触发执行检查。
单模块的maven项目只需要配置plugins即可, pom.xml配置如下:
org.apache.maven.plugins
maven-checkstyle-plugin
3.1.1
com.puppycrawl.tools
checkstyle
8.33
checkstyle.xml
UTF-8
true
true
false
validate
validate
check
org.springframework.boot
spring-boot-maven-plugin
org.apache.maven.plugins
maven-site-plugin
3.9.0
org.apache.maven.plugins
maven-checkstyle-plugin
多模块的maven项目,参考官方配置(https://maven.apache.org/plugins/maven-checkstyle-plugin/examples/multi-module-config.html),只需要在父模块的pom.xml里面配置插件即可,pom.xml配置如下
org.apache.maven.plugins
maven-checkstyle-plugin
3.1.1
com.example.whizbang
build-tools
1.0
Jenkins中使用Checkstyle,要先配置好maven的checkstyle(上面的步骤),然后编辑Jenkins的构建配置。
1.在Build的Goals and options中添加checkstyle:checkstyle,
2.再勾选构建配置的[Deprecated] Publish Checkstyle analysis results选项。
3.保存,重新构建项目,如果右边没有Checkstyle Trend显示,则重启一下Jenkins。


com.puppycrawl.tools.checkstyle.api.CheckstyleException:
cannot initialize module TreeWalker
- TreeWalker is not allowed as a parent of LineLength Please review
'Parent Module' section for this Check in web documentation if Check is standard.
查看官方文档,LineLength 这个属性需要放置在Checker里面的,但是网上很多示例是放到TreeWalker里面了。
Failed to execute goal org.apache.maven.plugins:maven-checkstyle-plugin:3.1.1:check
(validate) on project junitdemo: Failed during checkstyle configuration:
cannot initialize module TreeWalker - Token "INTERFACE_DEF" was not found
in Acceptable tokens list in check com.puppycrawl.tools.checkstyle.checks.blocks.RightCurlyCheck
在官方仓库中的google_checks.xml,使用了INTERFACE_DEF新增加的token,通过查看GitHub的提交记录可以看到,RightCurlyCheck在8.33的版本中还没有合并代码支持INTERFACE_DEF,所以直接去掉就可以了。
官方仓库:https://github.com/checkstyle/checkstyle
checks列表:https://checkstyle.org/checks.html
Maven插件:https://maven.apache.org/plugins/maven-checkstyle-plugin/