Classes annotated as @Controller in Spring are responsible for handling incoming web requests. When annotating methods or the entire
controller with @ResponseBody, the return value of said methods will be serialized and set as the response body. In other words, it tells
the Spring framework that this method does not produce a view. This mechanism is commonly used to create API endpoints.
Spring provides @RestController as a convenient annotation to replace the combination of @Controller and
@ResponseBody. The two are functionally identical, so the single annotation approach is preferred.
This rule will raise an issue on a class that is annotated with @Controller if:
@ResponseBody or @ResponseBody. Replace the @Controller annotation with the @RestController annotation and remove all @ResponseBody
annotations from the class and its methods.
@Controller
@ResponseBody
public class MyController {
@GetMapping("/hello")
public String hello() {
return "Hello World!";
}
}
@RestController
public class MyController {
@GetMapping("/hello")
public String hello() {
return "Hello World!";
}
}
@Controller
public class MyController {
@ResponseBody
@GetMapping("/hello")
public String hello() {
return "Hello World!";
}
@ResponseBody
@GetMapping("/foo")
public String foo() {
return "Foo";
}
}
@RestController
public class MyController {
@GetMapping("/hello")
public String hello() {
return "Hello World!";
}
@GetMapping("/foo")
public String foo() {
return "Foo";
}
}