SonarQube代码质量检测
SonarQube代码质量检测
SonarQube是业界领先的代码质量平台,支持30+语言的静态分析,帮助团队持续发现代码问题。
Maven集成
<!-- pom.xml -->
<properties>
<sonar.projectKey>my-project</sonar.projectKey>
<sonar.host.url>https://sonar.example.com</sonar.host.url>
<sonar.login>${env.SONAR_TOKEN}</sonar.login>
<sonar.coverage.jacoco.xmlReportPaths>
${project.build.directory}/site/jacoco/jacoco.xml
</sonar.coverage.jacoco.xmlReportPaths>
</properties>
运行扫描
# 本地运行
mvn clean verify sonar:sonar
# 带参数运行
mvn sonar:sonar \
-Dsonar.projectKey=my-project \
-Dsonar.host.url=https://sonar.example.com \
-Dsonar.token=$SONAR_TOKEN
质量门禁配置
// sonar-project.properties
sonar.projectKey=my-project
sonar.sources=src/main/java
sonar.tests=src/test/java
sonar.java.binaries=target/classes
sonar.java.libraries=target/dependency/*.jar
sonar.exclusions=**/generated/**,**/test/**
Java代码规则示例
// SonarQube常见问题检测
// 1. 空指针检查
// Bad: 可能NPE
public String getName(User user) {
return user.getName().toUpperCase(); // user可能为null
}
// Good: 安全访问
public String getName(User user) {
return Optional.ofNullable(user)
.map(User::getName)
.map(String::toUpperCase)
.orElse("UNKNOWN");
}
// 2. 资源泄露
// Bad: 未关闭资源
public String readFile(String path) throws IOException {
InputStream is = new FileInputStream(path);
return new String(is.readAllBytes());
}
// Good: try-with-resources
public String readFile(String path) throws IOException {
try (InputStream is = new FileInputStream(path)) {
return new String(is.readAllBytes());
}
}
// 3. 并发问题
// Bad: 非线程安全
public class Counter {
private int count = 0; // 缺少volatile或同步
public void increment() { count++; }
}
// Good: 线程安全
public class Counter {
private final AtomicInteger count = new AtomicInteger(0);
public void increment() { count.incrementAndGet(); }
}
CI/CD集成
# GitLab CI中集成SonarQube
sonar-scan:
stage: quality
image: sonarsource/sonar-scanner-cli:4.8
script:
- sonar-scanner
-Dsonar.projectKey=$CI_PROJECT_NAME
-Dsonar.host.url=$SONAR_HOST_URL
-Dsonar.login=$SONAR_TOKEN
-Dsonar.qualitygate.wait=true
自定义规则
// 自定义SonarQube规则示例
public class NoSystemOutCheck {
public void check(AstNode node) {
// 检测System.out.println调用
if (isMethodCall(node, "System", "out", "println")) {
context.addIssue(node, "禁止使用System.out,请使用日志框架");
}
}
}
小结
SonarQube通过自动化代码审查帮助团队持续改进代码质量,是CI/CD流程中不可或缺的质量关卡。