Maven CheckStyle Plugin集成

来源:互联网 发布:金英杰网络课程价格 编辑:程序博客网 时间:2024/05/17 03:50

一直以来都想规范化自己写的代码,近期自己写项目的时候终于尝试集成CheckStyle对代码进行自动检测。

在项目的pom.xml文件中,添加CheckStyle的Maven插件配置:

<project>......  <properties>    <maven.checkstyle.version>2.17</maven.checkstyle.version>  </properties>  <reporting>    <plugins>      <plugin>        <groupId>org.apache.maven.plugins</groupId>        <artifactId>maven-checkstyle-plugin</artifactId>        <version>${maven.checkstyle.version}</version>      </plugin>    </plugins>  </reporting>......</project>

Maven CheckStyle插件提供两种预先定义的规则:sun_checks.xml和google_checks.xml(http://checkstyle.sourceforge.net/google_style.html),默认提供的为sun_checks.xml。当然你也可以指定自定义的规则集。

google_checks.xml需要maven-checkstyle-plugin的version为2.17及以上

指定规则为google_checks.xml

<reporting>  <plugins>    <plugin>      <groupId>org.apache.maven.plugins</groupId>      <artifactId>maven-checkstyle-plugin</artifactId>      <version>${maven.checkstyle.version}</version>      <configuration>        <configLocation>google_checks.xml</configLocation>      </configuration>    </plugin>  </plugins></reporting>

CheckStyle插件可执行任务:

mvn checkstyle:help 查看帮助mvn checkstyle:check 查看工程是否满足检查。如果不满足,检查失败,可以通过target/checkstyle-result.xml来查看mvn checkstyle:checkstyle 查看工程是否满足检查。如果不满足,不会失败,可以通过target/site/checkstyle.html查看检查信息mvn checkstyle:checkstyle-aggregate 检查工程是否满足检查。如果不满足,不会失败,可以通过target/site/checkstyle.html查看

在用checkstyle命令检查之后,采用html的方式查看检查结果。结果中只会提示在哪一行,不能直接看代码。这时候可以添加Maven插件

<reporting>  <plugins>    <plugin>      <groupId>org.apache.maven.plugins</groupId>      <artifactId>maven-jxr-plugin</artifactId>      <version>${maven.jxr.version}</version>    </plugin>  </plugins></reporting>

执行mvn jxr:jxr之后,就可以查看对应的代码。