spring-mvc - SonarQube 提示将 ResponseEntity 与通配符一起使用

标签 spring-mvc spring-boot sonarqube

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

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

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

SonarQube 提示将 ResponseEntity 与通配符一起使用,向我报告了 严重问题“不应在返回参数中使用通用通配符类型” .

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

你怎么看待这件事?

最佳答案

@PostMapping
ResponseEntity<Object> addSomething(@RequestBody Some object) {
    // some code there
    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
这也将消除错误。它仍然非常通用,但是如果您想根据结果返回不同的类型,它是一种解决方案。例如:
@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);
    }

关于spring-mvc - SonarQube 提示将 ResponseEntity 与通配符一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44974384/

相关文章:

spring-boot - 从 Spring WebFlux 返回 Flux<String> 返回一个字符串而不是 JSON 中的字符串数组

java - JPA 在 Spring Boot 中导致 java.lang.NullPointerException

spring-boot - Spring Boot 2x 执行器 http 跟踪不跟踪主体

java - 从控制台和 jenkins 运行 Maven 目标有什么区别

java - 来自 Jenkins 的 Sonarqube 扫描 : ClassNotFoundException: org. eclipse.jgit.api.Git

maven - 使用Gradle,Jenkins和Sonar实现CI/CD Flow

java - Autowiring HttpSession 给出与 HttpServletRequest 不同的对象

java - 有什么简单的方法可以测试 @RequestBody 方法吗?

spring - Spring boot默认创建admin账号

java - HikariPool-1 - driverClassName 需要 jdbcUrl