rspec/rules/S6837/java/rule.adoc
github-actions[bot] ff6e32433a
Create rule S6837: Superfluous "@ResponseBody" annotations should be removed (#3366)
You can preview this rule
[here](https://sonarsource.github.io/rspec/#/rspec/S6837/java) (updated
a few minutes after each push).

## Review

A dedicated reviewer checked the rule description successfully for:

- [ ] logical errors and incorrect information
- [ ] information gaps and missing content
- [ ] text style and tone
- [ ] PR summary and labels follow [the
guidelines](https://github.com/SonarSource/rspec/#to-modify-an-existing-rule)

---------

Co-authored-by: johann-beleites-sonarsource <johann-beleites-sonarsource@users.noreply.github.com>
Co-authored-by: Johann Beleites <johann.beleites@sonarsource.com>
Co-authored-by: Johann Beleites <sdefend_9jftz8pq@esnail.de>
2023-10-31 16:45:13 +00:00

71 lines
1.8 KiB
Plaintext

== Why is this an issue?
The Spring framework's `@RestController` annotation is equivalent to using the `@Controller` and `@ResponseBody` annotations together.
As such, it is redundant to add a `@ResponseBody` annotation when the class is already annotated with `@RestController`.
== How to fix it
Remove the `@ResponseBody` annotation from the class or method.
=== Code examples
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
@RestController
public class MyController {
@ResponseBody // Noncompliant, the @RestController annotation already implies @ResponseBody
@RequestMapping("/hello")
public String hello() {
return "Hello World!";
}
}
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
@RestController
public class MyController {
@RequestMapping("/hello")
public String hello() {
return "Hello World!";
}
}
----
==== Noncompliant code example
[source,java,diff-id=2,diff-type=noncompliant]
----
@RestController
@ResponseBody // Noncompliant, the @RestController annotation already implies @ResponseBody
public class MyController {
@RequestMapping("/hello")
public String hello() {
return "Hello World!";
}
}
----
==== Compliant solution
[source,java,diff-id=2,diff-type=compliant]
----
@RestController
public class MyController {
@RequestMapping("/hello")
public String hello() {
return "Hello World!";
}
}
----
== Resources
=== Articles & blog posts
* Spring Guides - https://spring.io/guides/gs/rest-service/[Building a RESTful Web Service]
* Baeldung - https://www.baeldung.com/spring-controller-vs-restcontroller[The Spring @Controller and @RestController Annotations]
* Baeldung - https://www.baeldung.com/spring-request-response-body[Spring's RequestBody and ResponseBody Annotations]