跳到主要内容

CheckStyle插件使用

checkstyle插件使用

在pom文件中,使用maven-checkstyle-plugin插件,这样在执行mvn compile时会自动触发执行检查,参考文档1

单模块工程引入如下:

(多模块工程只需要在父模块的pom.xml中配置插件即可)

<build>
<pluginManagement>
<!-- 插件声明,不引入 -->
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<!-- 指定插件版本 -->
<version>${maven-checkstyle-plugin.version}</version>
<dependencies>
<!-- 指定依赖的checkstyle版本 -->
<dependency>
<groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId>
<version>${checkstyle.version}</version>
</dependency>
</dependencies>
<!-- 指定配置文件 -->
<configuration>
<suppressionsLocation>kuaishou-checkstyle-suppressions.xml</suppressionsLocation>
<configLocation>kuaishou-checkstyle.xml</configLocation>
<encoding>UTF-8</encoding>
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
<!--<linkXRef>false</linkXRef>-->
<sourceDirectories>
<directory>${project.build.sourceDirectory}</directory>
</sourceDirectories>
</configuration>
<executions>
<execution>
<id>validate</id>
<phase>validate</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<!-- 插件引入,不需要在指定版本 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
</plugin>
</plugins>
</build>

禁用checkstyle插件

某些时候,公司公共的parent文件里默认引入了checkstyle,但是本地因为历史原因,又没法开启,可以先本地使用如下配置,屏蔽掉checkstyle,避免在每次编译的时候都需要用命令跳过checkstyle mvn clean compile -Dcheckstyle.skip=true

<!-- 关闭 checkstyle 校验,请用户自行决定是否要开启 checkstyle -->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<executions>
<execution>
<id>validate</id>
<phase>none</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>

异常

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里面,很多的xml中,都放到TreeWalker里面了

参考

Footnotes

  1. Maven项目中使用CheckStyle检查代码