代码检查工具

1 checkstyle

   应用场景:检查Java源文件是否与代码规范相符,主要包括Javadoc注释,命名规范,多余没用的Imports,Size度量,如过长的方法,缺少必要的空格Whitespace,重复代码。

   应用配置:在POM文件的<reporting>标签中加入以下插件

   <plugin>

      <groupId>org.apache.maven.plugins</groupId>

      <artifactId>maven-checkstyle-plugins</artifactId>

      <version>2.16</version>

      <configuration>

          <configLocation>checkstyle.xml</configLocation>

      </configuration>

  </plugin>

  命令行:mvn chckstyle:chckstyle;

  结果显示:

                                 代码检查工具


2 findbugs

  应用场景: 基于Bug Patterns概念,查找CLASS文件中潜在的bug,主要检查NullPoint空指针检查,没有合理关闭资源,字符串相同判断错(==,而不是equals)等。

  应用配置:在POM文件的<reporting>标签中加入以下插件

   <plugin>

     <groupId>org.codehaus.mojo</groupId>

     <artifactId>findbugs-maven-plugin</artifactId>

     <version>2.5.2</version>    

  </plugin>

  命令行:mvn findbugs : findbugs;

  findbugs源码托管于SourceForge:https://sourceforge.net/projects/findbugs/files/findbugs/

  结果显示:(mvn findbugs:findbugs会生成findbugsXml.xml, 使用mvn site产生html文件便于查看)

  注意事项: findbugs执行时必须存在class文件,如果执行mvn clean 再执行findbugs就无法生成报告

代码检查工具

4 Sonar

  应用场景:与以上三种做特定代码检查的工具不同,Sonar是一个集成测试工具,可同时集成checkstyle,findbugs,pmd,并将检查结果处理后显示。

  源码:git clone git://github.com/SonarSource/sonar.git

 命令行:1 mvn clean install;

                 2 mvn sonar: sonar;

 功能说明: 1 maven插件会把Sonar所需数据(如单元测试结果、静态检测结果等)上传到 Sonar 服务器上

                     2 将 Soanr 所需要的数据上传到 Sonar 服务器上之后,Sonar 安装的插件会对这些数据进行分析和处理,并以各种方式显示给用户,从而使用户方便地对代码质量的监测和管理

 Sonar在线演示系统:http://sonar.oschina.net/

 Sonar的不足:不适用与高并发的场景,配置比较复杂。

 应用配置:Sonar 的配置并不在每个工程的 pom.xml 文件里,而是在 Maven 的配置文件 settings.xml 

 <profile>
   <id>sonar</id>
   <activation>
       <activeByDefault>true</activeByDefault>
   </activation>
   <properties>
        <sonar.jdbc.url>
        jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8
        </sonar.jdbc.url>
        <sonar.jdbc.driver>com.mysql.jdbc.Driver</sonar.jdbc.driver>
        <sonar.jdbc.username>sonar</sonar.jdbc.username>
        <sonar.jdbc.password>sonar</sonar.jdbc.password>
       <sonar.host.url>http://localhost:9000</sonar.host.url>
   </properties>
 </profile>