SpotBugs是FindBugs的继任者,从SpotBugs停止的地方继续。
备注:FindBugs项目已经停止了,从2015年发布3.0.1版本以后再没有新的版本。
SpotBugs通过静态分析寻找java代码中的bug,通过发现bug模式来发现疑似问题。
它是一款免费软件,是FindBugs的一个分支。
https://spotbugs.readthedocs.io/en/latest/index.html
https://spotbugs.github.io/
https://github.com/spotbugs/spotbugs
SpotBugs是用JDK8版本构建的,所以运行需要JRE (或 JDK) 1.8.0及以后的版本。
SpotBugs可以扫描JDK8及更新的版本编译生成的字节码(即class文件)。
SpotBugs 可以检查400多种bug模式,分了10个大的类别:
https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html
https://spotbugs.readthedocs.io/en/latest/detectors.html#
Standard detectors默认是打开的,而Disabled detectors默认是关闭的。
要在Eclipse中安装SpotBugs Plugin,需要 Eclipse Neon (4.6) 及以后版本。
我们用Eclipse Marketplace来安装,下面是安装步骤:
点击Restart Now,重新进入Eclipse。
从菜单Window->Preferences进入,在Java下面出现SpotBugs项,说明安装成功了:
从菜单Window->Preferences进入,在Java下面找到SpotBugs项:
在Reporter Configuraton页面,可以选择报告的bug类别:
https://spotbugs.readthedocs.io/en/latest/effort.html
effort的值是调节了SpotBugs的内部flag,通过降低预测来降低计算成本。
在Filter files页面可以配置包含filter文件、不包含filter文件。其中filter文件的介绍请参见:
https://spotbugs.readthedocs.io/en/latest/filter.html
在Detector configuration页面,可以勾选或者不勾选某个/某些检测器:
检测器的信息跟SpotBugs官网中的detector对应:
如果要启用项目特有的配置,就在Enable project specific settings复选框打钩:
在项目上右击,在弹出菜单中选择Properties。在属性设置界面选中左侧的SpotBugs。
如果要自动运行,就在Run automatically复选框打钩,这样每次修改了项目中的类,SpotBug就会自动运行:
右击java项目,在弹出菜单中选择SpotBugs->Find Bugs,就会立即扫描:
右击java项目,在弹出菜单中选择SpotBugs->Save XML:
打开该文件看看内容片段(文件内容远比在Eclipse Problems窗口中显示的信息丰富):
https://spotbugs.readthedocs.io/en/latest/maven.html
在maven工程的pom.xml文件中build小节、reporting小节增加关于SpotBugs Maven插件的配置信息:
com.github.spotbugs
spotbugs-maven-plugin
4.7.3.5
com.github.spotbugs
spotbugs-maven-plugin
true
com.github.spotbugs
spotbugs-maven-plugin
true
等待一会儿,插件及其依赖的SpotBugs版本下载到maven本地仓库了:
https://spotbugs.github.io/spotbugs-maven-plugin/spotbugs-mojo.html
用SpotBugs分析目标工程,其中很多参数可以调节、控制分析。
备注:该goal本身没有将java文件编译为class文件的动作。
示例:
先调用mvn compile进行编译,然后调用mvn spotbugs:spotbugs进行分析:
到maven工程的target目录下查看输出内容:
打开spotbugs.html查看输出结果:
https://spotbugs.github.io/spotbugs-maven-plugin/check-mojo.html
用SpotBugs分析目标工程,如果发现问题,就停止构建。
示例:
先调用mvn compile进行编译,然后调用mvn spotbugs:check:
https://spotbugs.github.io/spotbugs-maven-plugin/gui-mojo.html
调用 SpotBugs GUI(图形用户界面)显示分析结果。
备注:要先用其它的goal生成分析结果,再调用此goal显示分析结果。
示例:
先调用mvn compile进行编译,然后调用mvn spotbugs:spotbugs进行扫描分析、最后调用mvn spotbugs:gui拉起SpotBugs的图形用户界面显示分析结果:
显示帮助信息。