SonarQube integration with Spring Boot

✅ What is SonarQube?

SonarQube is an open-source code quality and security analysis tool. It scans your source code to detect:

  • Bugs 🐞
  • Code smells 🧹
  • Vulnerabilities 🔓
  • Duplications 🔁
  • Test coverage 📊

It supports Java, Python, JavaScript, and many other languages.


🚀 Why Use SonarQube?

Feature Benefit
Static Code Analysis Catch issues before runtime
Code Quality Gates Block bad code from going to production
Custom Rules Enforce team standards and best practices
Integration Works with CI tools (Jenkins, GitHub Actions, etc.)

 


⚙️ How to Use SonarQube with Spring Boot

🔧 1. Install SonarQube

You can install it locally using Docker:

docker run -d --name sonarqube -p 9000:9000 sonarqube:latest

Access UI at: http://localhost:9000
(Default login: admin / admin)


📦 2. Add Sonar Plugin to pom.xml (for Maven)

<plugin>
  <groupId>org.sonarsource.scanner.maven</groupId>
  <artifactId>sonar-maven-plugin</artifactId>
  <version>3.9.1.2184</version>
</plugin>


🧪 3. Analyze Your Spring Boot Project

Run this command from your project root:

mvn clean verify sonar:sonar \
  -Dsonar.projectKey=my-springboot-app \
  -Dsonar.host.url=http://localhost:9000 \
  -Dsonar.login=your_sonarqube_token

You can create a token in the SonarQube UI → My Account → Security


📄 4. View Results

Open http://localhost:9000/projects and view the scan results:

  • Bugs, vulnerabilities, code smells
  • Code coverage (if tests and coverage plugins are configured)

✅ Optional: Generate Coverage Reports (Jacoco for Java)

Add to pom.xml:

<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.8.8</version>
    <executions>
        <execution>
            <goals>
                <goal>prepare-agent</goal>
            </goals>
        </execution>
        <execution>
            <id>report</id>
            <phase>verify</phase>
            <goals>
                <goal>report</goal>
            </goals>
        </execution>
    </executions>
</plugin>

🧠 Best Practices

  • Set quality gates to block bad code
  • Integrate with CI/CD pipeline (Jenkins, GitHub Actions)
  • Run Sonar scans regularly during development
  • Customize rules to match your team’s coding standards
Back to blog

Leave a comment