SonarQube 抱怨使用带有通配符的 ResponseEntity

Ily*_*ich 9 spring-mvc spring-boot sonarqube

我使用 SpringBoot 进行 REST Web 服务开发,使用 SonarQube 进行静态分析。

我的应用程序中有一些端点,如下所示:

@PostMapping
ResponseEntity<?> addSomething(@RequestBody Some object) {
    // some code there
    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
Run Code Online (Sandbox Code Playgroud)

SonarQube 抱怨使用带有通配符的 ResponseEntity,向我报告了一个严重问题“通用通配符类型不应在返回参数中使用”

我想知道是否应该在 SonarQube 中禁用此验证,或者为这些情况提供不同的返回类型。

你怎么看待这件事?

Ale*_*nov 6

@PostMapping
ResponseEntity<Object> addSomething(@RequestBody Some object) {
    // some code there
    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
Run Code Online (Sandbox Code Playgroud)

这也将消除该错误。它仍然非常通用,但如果您想根据结果返回不同类型,它是解决方案之一。例如:

@PostMapping
    ResponseEntity<Object> addSomething(@RequestBody Some object) {

        //Will return ResponseEntity<> with errors
        ResponseEntity<Object> errors = mapValidationService(bindingResult);
        if (!ObjectUtils.isEmpty(errors)) return errors;
        
        // some code there
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
Run Code Online (Sandbox Code Playgroud)


Ily*_*ich -6

最后,我从返回值中删除了<?>,因此代码现在如下所示:

@PostMapping
ResponseEntity addSomething(@RequestBody Some object) {
    // some code there
    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
Run Code Online (Sandbox Code Playgroud)

SonarQube 不再抱怨,代码现在看起来更简单了一些。

  • 在这种情况下,消息更改为:“为此泛型提供参数化类型。” (4认同)