Java Code Quality and Static Analysis with SonarQube
Jul 29, 2025 am 02:03 AMSonarQube is an open source code quality management platform used to detect code defects, security vulnerabilities, code odors, duplicate code in more than 20 languages such as Java, and evaluate test coverage and complexity. 1. Install the SonarQube server and access http://localhost:9000 to complete initialization; 2. Configure the SonarScanner tool or use the Maven/Gradle plug-in; 3. Create the sonar-project.properties file in the project root directory, specify the project information, source code path, compilation output and test report path; 4. Use Jacoco to generate a test coverage report, and configure prepare-agent and report execution through the Maven plug-in; 5. Run the mvn clean verify sonar:sonar or sonar-scanner command, and submit the analysis results in combination with the -Dsonar.login token authentication. Key rules include avoiding empty catch blocks, controlling circle complexity, eliminating duplicate code, ensuring more than 80% test coverage, and handling security hotspots. Quality access control can be enforced in CI processes such as Jenkins or GitHub Actions via custom quality thresholds (such as new code coverage ≥80%, zero serious problems, duplicate code
Java code quality and static analysis are key links to ensure long-term maintainability and stability of projects, and SonarQube is one of the most popular code quality management platforms at present. It can help development teams automatically detect potential flaws, code odors, security vulnerabilities and duplicate code in code, thereby continuously improving code quality.

What is SonarQube?
SonarQube is an open source platform for continuous inspection of code quality. It supports more than 20 programming languages including Java, and provides insights into the following dimensions by statically analyzing source code:
- Bug detection : Found a code problem that may cause runtime errors.
- Vulnerability identification : Detect security issues, such as SQL injection, hard-coded passwords, etc.
- Code Smell : Points out code with poor structure and difficult to maintain.
- Repeat code : Identify duplicate code blocks to reduce maintenance costs.
- Test coverage : Integrate unit test reports to evaluate code coverage.
- Complexity analysis : measure the circle complexity of classes and methods to avoid excessive complexity.
How to integrate SonarQube into Java project?
To apply SonarQube to a Java project, the following steps are usually required:

-
Install and start the SonarQube server
- Download SonarQube (Community Edition for free) and start the service (default port 9000).
- Visit
http://localhost:9000
to complete the initial configuration.
-
Configure SonarScanner
- SonarScanner is a command-line tool for performing analysis and needs to be downloaded and configured into the system path.
- Or use the Maven/Gradle plug-in to integrate more easily.
-
Add configuration files to the project
-
Create a
sonar-project.properties
file in the project root directory, content example:sonar.projectKey=my-java-project sonar.projectName=My Java Project sonar.projectVersion=1.0 sonar.sources=src/main/java sonar.tests=src/test/java sonar.java.binaries=target/classes sonar.java.test.binaries=target/test-classes sonar.junit.reportPaths=target/surefire-reports sonar.jacoco.reportPaths=target/jacoco.exec
-
Generate code coverage report (Jacoco recommended)
If using Maven, add the Jacoco plugin:
<plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.8.11</version> <executions> <execution> <goals> <goal>prepare-agent</goal> </goals> </execution> <execution> <id>report</id> <phase>test</phase> <goals> <goal>report</goal> </goals> </execution> </executions> </plugin>
Running analysis
- Execute the command:
mvn clean verify sonar:sonar \ -Dsonar.login=your-token \ -Dsonar.host.url=http://localhost:9000
- Or use SonarScanner:
sonar-scanner -Dsonar.login=your-token
- Execute the command:
Note: It is recommended to use the user token generated by SonarQube for authentication, rather than the plaintext username and password.
Key Quality Rules and Best Practices
SonarQube has hundreds of rules built in, and here are some that are particularly worthy of attention in Java projects:
Avoid empty catch blocks
catch(Exception e) {}
will mask the exception and should at least log logs.Reduce circle complexity (Cyclomatic Complexity)
The method is too complex (default > 10 alarms) means it is difficult to test and maintain, and the logic should be split.Eliminate duplicate code
SonarQube will mark similar code blocks, prompting to extract public methods or classes.Ensure unit test coverage
It is recommended to set a minimum coverage threshold (such as row coverage ≥80%) and to be mandatory checks in the CI process.Security Hotspots
Such as hard-coded credentials, unsafe random number generation (Math.random()
is used in safe scenarios), etc.
You can customize quality thresholds in the SonarQube interface, for example:
- The coverage rate of new codes is ≥ 80%
- Zero serious (Blocker) problem
- Number of repeated lines of code
These rules can be enforced in the project continuous integration (CI) process, such as integrating SonarQube scans in Jenkins or GitHub Actions, and blocking merges if they fail.
Tips: Avoid common pitfalls
Compiled classpath configuration error
Make suresonar.java.binaries
points to the correct compiled output directory (such astarget/classes
), otherwise some rules will not take effect.The test report path is incorrect
Ifsonar.junit.reportPaths
andsonar.jacoco.reportPaths
are not configured correctly, the coverage will be displayed as 0.Incremental analysis vs full analysis
SonarQube performs full analysis by default. If you only analyze the change code, you can usesonar-scm-provider-git
plug-in to cooperate.Chinese annotations lead to coding problems
Ensure that the source code file is UTF-8 encoding to avoid analysis failures due to character set problems.
Basically that's it. What makes SonarQube powerful is that it turns code quality into a measurable and traceable process. For Java projects, integrating SonarQube is not complicated, but the long-term benefits are very significant - fewer online bugs, better maintainability, and more efficient teamwork.
The above is the detailed content of Java Code Quality and Static Analysis with SonarQube. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Maven is a standard tool for Java project management and construction. The answer lies in the fact that it uses pom.xml to standardize project structure, dependency management, construction lifecycle automation and plug-in extensions; 1. Use pom.xml to define groupId, artifactId, version and dependencies; 2. Master core commands such as mvnclean, compile, test, package, install and deploy; 3. Use dependencyManagement and exclusions to manage dependency versions and conflicts; 4. Organize large applications through multi-module project structure and are managed uniformly by the parent POM; 5.

SetupaMaven/GradleprojectwithJAX-RSdependencieslikeJersey;2.CreateaRESTresourceusingannotationssuchas@Pathand@GET;3.ConfiguretheapplicationviaApplicationsubclassorweb.xml;4.AddJacksonforJSONbindingbyincludingjersey-media-json-jackson;5.DeploytoaJakar

First, use JavaScript to obtain the user system preferences and locally stored theme settings, and initialize the page theme; 1. The HTML structure contains a button to trigger topic switching; 2. CSS uses: root to define bright theme variables, .dark-mode class defines dark theme variables, and applies these variables through var(); 3. JavaScript detects prefers-color-scheme and reads localStorage to determine the initial theme; 4. Switch the dark-mode class on the html element when clicking the button, and saves the current state to localStorage; 5. All color changes are accompanied by 0.3 seconds transition animation to enhance the user

Understand the core components of blockchain, including blocks, hashs, chain structures, consensus mechanisms and immutability; 2. Create a Block class that contains data, timestamps, previous hash and Nonce, and implement SHA-256 hash calculation and proof of work mining; 3. Build a Blockchain class to manage block lists, initialize the Genesis block, add new blocks and verify the integrity of the chain; 4. Write the main test blockchain, add transaction data blocks in turn and output chain status; 5. Optional enhancement functions include transaction support, P2P network, digital signature, RESTAPI and data persistence; 6. You can use Java blockchain libraries such as HyperledgerFabric, Web3J or Corda for production-level opening

@property decorator is used to convert methods into properties to implement the reading, setting and deletion control of properties. 1. Basic usage: define read-only attributes through @property, such as area calculated based on radius and accessed directly; 2. Advanced usage: use @name.setter and @name.deleter to implement attribute assignment verification and deletion operations; 3. Practical application: perform data verification in setters, such as BankAccount to ensure that the balance is not negative; 4. Naming specification: internal variables are prefixed, property method names are consistent with attributes, and unified access control is used to improve code security and maintainability.

To generate hash values using Java, it can be implemented through the MessageDigest class. 1. Get an instance of the specified algorithm, such as MD5 or SHA-256; 2. Call the .update() method to pass in the data to be encrypted; 3. Call the .digest() method to obtain a hash byte array; 4. Convert the byte array into a hexadecimal string for reading; for inputs such as large files, read in chunks and call .update() multiple times; it is recommended to use SHA-256 instead of MD5 or SHA-1 to ensure security.

Yes, a common CSS drop-down menu can be implemented through pure HTML and CSS without JavaScript. 1. Use nested ul and li to build a menu structure; 2. Use the:hover pseudo-class to control the display and hiding of pull-down content; 3. Set position:relative for parent li, and the submenu is positioned using position:absolute; 4. The submenu defaults to display:none, which becomes display:block when hovered; 5. Multi-level pull-down can be achieved through nesting, combined with transition, and add fade-in animations, and adapted to mobile terminals with media queries. The entire solution is simple and does not require JavaScript support, which is suitable for large

Use datetime.strptime() to convert date strings into datetime object. 1. Basic usage: parse "2023-10-05" as datetime object through "%Y-%m-%d"; 2. Supports multiple formats such as "%m/%d/%Y" to parse American dates, "%d/%m/%Y" to parse British dates, "%b%d,%Y%I:%M%p" to parse time with AM/PM; 3. Use dateutil.parser.parse() to automatically infer unknown formats; 4. Use .d
