使用SpotBugs/FindBugs进行代码检查

原po:https://blog.csdn.net/zhangb00/article/details/8407070

SpotBugs 介绍
  SpotBugs是Findbugs的继任者(Findbugs已经于2016年后不再维护,see https://mailman.cs.umd.edu/pipermail/findbugs-discuss/2016-November/004321.html),用于对代码进行静态分析,查找相关的漏洞。

  目前SpotBugs 3.1.3 自带检测器,其中有90余种Bad practice,155余种Correctness,9种Experimental, 2种 Internationalization,17种Malicious code vulnerability,46种Multithreaded correctness,4种 Bogus random noise,37种Performance,11种 Security,87种Dodgy。

  Bad practice 不佳实践:常见代码错误,用于静态代码检查时进行缺陷模式匹配(如重写equals但没重写hashCode,或相反情况等)
  Correctness 可能导致错误的代码(如空指针引用、无限循环等)
  Experimental 实验性
  Internationalization 国际化相关问题(如错误的字符串转换等)
  Malicious code vulnerability 可能受到的恶意攻击(如访问权限修饰符的定义等)
  Multithreaded correctness 多线程的正确性(如多线程编程时常见的同步,线程调度问题等)
  BogusMultithreaded correctness 多线程的正确性(如多线程编程时常见的同步,线程调度问题等)
  Performance 运行时性能问题(如由变量定义,方法调用导致的代码低效问题等)
  Security 安全问题(如HTTP,SQL,DB等)
  Dodgy code 导致自身错误的代码(如未确认的强制转换、冗余的空值检查等)
注: SpotBugs 需要当前的JDK环境为 1.8以上,但可以对1.0~1.9的代码来进行检查。

SpotBugs 插件
  SpotBugs 还有对应的额外插件,用于扩展对应的规则,探测出更多的代码问题。

  fb-contrib
  目前最新为7.4.3,增加了大致130+条规则;其中因 FindBugs分叉,SpotBugs需要使用-sb版本。
  官网 : https://github.com/mebigfatguy/fb-contrib

find-sec-bugs
目前最新为 1.8.0,针对安全(Security)增加了大致70+条规则
官网: https://github.com/find-sec-bugs/find-sec-bugs

SpotBugs 使用
Maven
maven 插件方式使用 spotbugs及相关插件

<plugin>
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs-maven-plugin</artifactId>
<version>3.1.1</version>
<configuration>
<plugins>
<plugin>
<groupId>com.h3xstream.findsecbugs</groupId>
<artifactId>findsecbugs-plugin</artifactId>
<version>LATEST</version>
</plugin>
<plugin>
<groupId>com.mebigfatguy.fb-contrib</groupId>
<artifactId>fb-contrib</artifactId>
<version>7.4.3.sb</version>
</plugin>
</plugins>
</configuration>
</plugin>

IDE环境
Eclipse
请在对应的marketplace 搜索或install new software来进行spotbugs的安装,正式版本的安装路径 https://spotbugs.github.io/eclipse/

安装插件后,可以在对应的Preferences 进行更多SpotBugs plugin安装,参考如下图:


可以通过以下网址获取最新的插件jar
https://mvnrepository.com/artifact/com.mebigfatguy.fb-contrib/fb-contrib
https://mvnrepository.com/artifact/com.h3xstream.findsecbugs/findsecbugs-plugin

完成安装后,可以对java工程或者对应的类,右键进行 SpotBugs ->Find Bugs


JetBrain IDEA
目前没有SpotBugs插件,原FindBugs插件作者、IDEA还在讨论商标问题,请先使用 原有FindBugs代替。
https://github.com/andrepdo/findbugs-idea/issues/265
https://youtrack.jetbrains.com/issue/IDEA-201846

其他
其他更多内容可以参考SpotBugs 官方文档
https://spotbugs.readthedocs.io/en/latest/installing.html
---------------------
作者:zhangb00
来源:CSDN
原文:https://blog.csdn.net/zhangb00/article/details/84070706
版权声明:本文为博主原创文章,转载请附上博文链接!

原文地址:https://www.cnblogs.com/XYYCKL/p/10320561.html