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

时间:2017-07-07 15:19:34

标签: spring-mvc spring-boot sonarqube

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

我的应用程序中有几个端点看起来如下:

{{1}}

SonarQube抱怨将ResponseEntity与通配符一起使用,向我报告严重问题"通用通配符类型不应用于返回参数"

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

你怎么看?

3 个答案:

答案 0 :(得分:1)

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

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

SonarQube不再抱怨了,现在代码似乎有点简单了。

答案 1 :(得分:1)

@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);
    }

答案 2 :(得分:0)

所以实际上我发现规则非常自我描述:

  

隐式使用通配符作为返回类型意味着返回值应被视为只读,但无法执行此合同。

     

我们举一个返回&#34; List&#34;的方法的例子。在此列表中是否可以添加狗,猫,......我们根本不知道。方法的消费者不应该处理这种破坏性问题。

     

https://sonarcloud.io/organizations/default/rules#rule_key=squid%3AS1452

所以实际上在你的情况下,你不希望那里有任何类,你特别想要一个Serializable - 对象 - 原因显而易见:它应该在以后序列化

因此,在您使用?时更适合使用Serializable。这始终取决于案例,但通常您肯定期望某种通用接口或基类作为返回值。因此,后续开发人员肯定知道他可以期待什么,以及他明确可以使用哪种功能。