第一步:下载安装包
https://www.sonarsource.com/products/sonarqube/downloads/
下载完成后会得到如下的压缩包
第二步:解压和修改配置
将其解压到某路径下,并修改sonarqube-10.1.0.73491\conf\sonar.properties文件,主要是修改数据库连接
这里使用的是PostgreSQL数据库,至于数据库如何安装可以参考Windows下安装PostgreSQL 15
启动sonar前记得在数据库中创建好配置的schema
第三步:启动Sonar
进入目录“sonarqube-10.1.0.73491\bin\windows-x86-64”执行StartSonar.bat脚本
如果没报错,访问http://localhost:9000
使用默认的admin/admin进行登录。第一次会要求修改密码
如果启动过程有误,请查看输出的日志,有可能因为数据库连接、端口暂用等问题导致sonar退出
第四步:创建验证项目
自行创建maven项目,并在pom文件中添加插件
<build>
<plugins>
<!--
mvn clean verify sonar:sonar
mvn clean verify sonar:sonar -Dsonar.token=myAuthenticationToken
-->
<plugin>
<groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>3.9.1.2184</version>
</plugin>
</plugins>
</build>
第五步:修改setting.xml文件
找到maven的setting.xml配置文件,并按以下进行修改
<pluginGroups>
<pluginGroup>org.sonarsource.scanner.maven</pluginGroup>
</pluginGroups>
<profiles>
<profile>
<id>sonar</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<sonar.host.url>http://localhost:9000</sonar.host.url>
<sonar.language>java</sonar.language>
<!--
[WARNING] The properties 'sonar.login'
and 'sonar.password' are deprecated and will be
removed in the future. Please pass a token with
the 'sonar.token' property instead.
-->
<sonar.login>admin</sonar.login>
<sonar.password>root123</sonar.password>
</properties>
</profile>
</profiles>
<activeProfiles>
<activeProfile>sonar</activeProfile>
</activeProfiles>
第六步:执行代码扫描
往项目中添加一些代码,然后执行mvn clean verify sonar:sonar
命令
构建构成成功,同时也打印了查看报告的访问地址,同时在target路径下也输出了相应信息
访问地址便可查看报表
说明:以上只是初步的搭建使用,而且还只是基于maven方式的,至于其原理和如何自定义规则等,在后续逐步输出