以下示例描述了 Checkstyle 插件的基本用法。
要生成 Checkstyle 报告作为项目报告的一部分,请在pom.xml的<reporting>部分添加 Checkstyle 插件。
<project> ... <reporting> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <version>3.1.2</version> <reportSets> <reportSet> <reports> <report>checkstyle</report> </reports> </reportSet> </reportSets> </plugin> </plugins> </reporting> ... </project>
然后,执行站点阶段以生成报告。
mvn site
您还可以通过从命令行显式执行checkstyle:checkstyle目标来生成 Checkstyle 报告。除非您想使用特定配置,否则您不需要在pom.xml中指定 Checkstyle 插件。
mvn checkstyle:checkstyle
如果您想向控制台报告或构建失败,您必须将checkstyle::check的执行添加到<build>元素并配置您需要的任何选项。
您在<reporting>元素中设置的选项对<build>元素中的执行没有任何影响。
注意checkstyle::check绑定的阶段非常重要。如果绑定到验证阶段,它将在编译代码之前检查代码。如果代码无效,则 checkstyle 报告的解析错误可能与 javac 编译器预期的不同。但是,它可以保证运行。另一个流行的选项是将它绑定到稍后运行的验证阶段(并允许 javac 编译器在 checkstyle 之前标记无效代码)。但是,如果开发人员通常只在推送更改之前使用“mvn test”,则 checkstyle 将不会运行,因为 verify 发生在测试阶段之后。
例如:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <version>3.1.2</version> <configuration> <configLocation>checkstyle.xml</configLocation> <encoding>UTF-8</encoding> <consoleOutput>true</consoleOutput> <failsOnError>true</failsOnError> <linkXRef>false</linkXRef> </configuration> <executions> <execution> <id>validate</id> <phase>validate</phase> <goals> <goal>check</goal> </goals> </execution> </executions> </plugin>