71 lines
1.8 KiB
Plaintext
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]
|