代码检查工具

本文介绍Checkstyle、FindBugs及Sonar等工具的应用场景、配置方法及如何集成这些工具来提高代码质量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 >




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值