我正在开始一个新项目,我需要使用SonarQube,我想使用Lombok,我已经在Eclipse中配置它,一切正常,除了静态分析.
@Data类时,所有字段都被报告为Unused private field.@Getter(lazy=true):当我使用此批注我得到的Redundant nullcheck of value known to be non-null 看@Getter(懒惰=真)(这是关系到编译后的代码).我认为一个可能的解决方案是delombok项目,编译并运行Sonar.
类似问题SonarQube Jira:
(@SuppressWarnings("PMD.UnusedPrivateField")解决方案不适用于最新SonarQube 4.2)
我怎么解决这个问题?
作为一种解决方法,我现在让声纳对delombok生成的代码进行分析.
我想这也不是一个完美的解决方案,因为我正在分析生成的代码而不是实际由开发人员编写的代码.我发现它比使用@SuppressWarnings, //NOSONAR或关闭Sonar本身的规则更好.
请参阅下面的示例以在Maven中实现此目的.将其添加到您的pom.xml:
<properties>
...
<!-- This is exposed as a workaround to do the sonar analysis in combination with delombok -->
<src.dir>src/main/java</src.dir>
...
</properties>
...
<plugins>
...
<plugin>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-maven-plugin</artifactId>
<version>${lombok-plugin.version}</version>
<executions>
<execution>
<phase>verify</phase>
<goals>
<goal>delombok</goal>
</goals>
<configuration>
<addOutputDirectory>false</addOutputDirectory>
<sourceDirectory>src/main/java</sourceDirectory>
</configuration>
</execution>
</executions>
</plugin>
...
</plugins>
...
<profiles>
...
<profile>
<!-- we have to use this profile to analyse code with sonar until https://jira.codehaus.org/browse/MSONAR-70 is fixed ! -->
<id>sonar</id>
<properties>
<src.dir>target/generated-sources/delombok</src.dir>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-maven-plugin</artifactId>
<version>${lombok-plugin.version}</version>
<executions>
<execution>
<phase>verify</phase>
<goals>
<goal>delombok</goal>
</goals>
<configuration>
<addOutputDirectory>true</addOutputDirectory>
<sourceDirectory>src/main/java</sourceDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>2.2</version>
</plugin>
</plugins>
</build>
</profile>
...
</profiles>
Run Code Online (Sandbox Code Playgroud)
我前段时间问过类似的问题: sonarqube 4.2 and lombok
基本上,您不能再在代码中使用注释(如@SuppressWarnings)来做到这一点。相反,您需要在 SonarQube 中设置(全局)规则排除:
单击“设置”->“排除”->“问题”,然后在“忽略多个条件的问题”部分中添加条目,然后输入如下内容:
Rule Key Pattern File Path Pattern
squid:S1068 **/models/**/*.java
Run Code Online (Sandbox Code Playgroud)
它使您的源代码更加干净(因为您不再需要@SuppressWarnings),但我不喜欢设置全局规则的想法,因为它可能会导致其他问题。
更新:
对于“已知非空值的冗余空检查”,您可以添加如下内容:
Rule Key Pattern File Path Pattern
findbugs:RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE **/xxxxx.java
Run Code Online (Sandbox Code Playgroud)
另一种可能(或可能没有)对您有用:
Rule Key Pattern File Path Pattern
common-java:InsufficientBranchCoverage **/models/**/*.java
Run Code Online (Sandbox Code Playgroud)