Sonar是一个用于代码质量管理的开源平台,用于管理Java源代码的质量。通过插件机制,Sonar 可以集成不同的测试工具,代码分析工具,以及持续集成工具,比如pmd-cpd、checkstyle、findbugs、Jenkins。通过不同的插件对这些结果进行再加工处理,通过量化的方式度量代码质量的变化,从而可以方便地对不同规模和种类的工程进行代码质量管理。 同时 Sonar 还对大量的持续集成工具提供了接口支持,可以很方便地在持续集成中使用 Sonar。 此外,Sonar 的插件还可以对 Java 以外的其他编程语言提供支持,对国际化以及报告文档化也有良好的支持。sonar官网:http://www.sonarqube.org/
下载sonar3.7.4,地址为http://dist.sonar.codehaus.org/sonar-3.7.4.zip
1) 创建数据库,使用 CREATE DATABASE sonar_test
2) 编辑${SONAR_HOME}/conf/sonar.properties配置数据库:
sonar.jdbc.username: sonar
sonar.jdbc.password: sonar
sonar.jdbc.url:
jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true
# Optional properties
sonar.jdbc.driverClassName: com.mysql.jdbc.Driver
3)配置DB驱动包
如果使用Oracle数据库,必须手动复制驱动类到${SONAR_HOME}/extensions/jdbc-driver/oracle/目录下
4) 添加语言包后
下载sonar-l10n-zh-plugin-1.5.jar,将包放置到extensions\plugins\ 目录下安装
5) 运行如下命令启动sonar,其它操作系统sonar均提供了启动脚本
${SONAR_HOME}/bin/linux-x86-64/sonar.sh start
6) 浏览器中访问: http://localhost:9000 管理员帐号和密码为:admin/admin
修改maven的主配置文件(${MAVEN_HOME}/conf/settings.xml文件或者 ~/.m2/settings.xml文件),在其中增加访问Sonar数据库及Sonar服务地址,添加如下配置:
<profiles>
<profile>
<id>sonar</id>
<properties>
<sonar.jdbc.url>jdbc:mysql://localhost:3306/sonar_morly_test</sonar.jdbc.url>
<sonar.jdbc.driver>com.mysql.jdbc.Driver</sonar.jdbc.driver>
<sonar.jdbc.username>root</sonar.jdbc.username>
<sonar.jdbc.password></sonar.jdbc.password>
<sonar.host.url>http://localhost:9000</sonar.host.url> <!-- Sonar服务器访问地址 -->
</properties>
</profile>
</profiles>
<activeProfiles>
<activeProfile>sonar</activeProfile>
</activeProfiles>
使用Sonar, 在项目中的pom.xml中添加如下,接着通过 mvn sonar:sonar 将代码注入到Sonar中进行分析处理,并将处理结果以XML的形式保存在数据库中;通过浏览器访问,显示分析结果;
<build>
<plugins>
<plugin>
<groupId>org.codehaus.sonar</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>3.7.1</version>
</plugin>
</plugins>
</build>
在jenkins的插件管理中选择安装sonar jenkins plugin,该插件可以使项目每次构建都调用sonar进行代码度量。
1) 进入配置页面对sonar插件进行配置
2) 配置构建项目,增加Post Build Action
3) 应用程序构建时就会自动触发Sonar对代码的检查
© 2015 Morly Tang. All Rights Reserved.
版权归属:寂寞的男人