使用SpotBugs 进行代码检查

SpotBugs作为Findbugs的继任者,用于静态代码分析,检测潜在漏洞。它包括多种检测器,覆盖不佳实践、正确性、性能等问题,并支持1.0至1.9的Java代码。可通过Maven插件或IDE集成使用。

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

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。

  1. Bad practice 不佳实践:常见代码错误,用于静态代码检查时进行缺陷模式匹配(如重写equals但没重写
    hashCode,或相反情况等)
  2. Correctness 可能导致错误的代码(如空指针引用、无限循环等)
  3. Experimental 实验性
  4. Internationalization 国际化相关问题(如错误的字符串转换等)
  5. Malicious code vulnerability 可能受到的恶意攻击(如访问权限修饰符的定义等)
  6. Multithreaded correctness 多线程的正确性(如多线程编程时常见的同步,线程调度问题等)
  7. BogusMultithreaded correctness 多线程的正确性(如多线程编程时常见的同步,线程调度问题等)
  8. Performance 运行时性能问题(如由变量定义,方法调用导致的代码低效问题等)
  9. Security 安全问题(如HTTP,SQL,DB等)
  10. 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

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

  2. 安装插件后,可以在对应的Preferences 进行更多SpotBugs plugin安装,参考如下图:
    在这里插入图片描述

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

  3. 完成安装后,可以对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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值