Use @RestController instead of @Controller + @ResponseBody
ID |
java.spring_use_restcontroller |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Best Practice |
Language |
Java |
Tags |
best-practice, code-style, spring |
Description
Reports classes annotated with both @Controller and @ResponseBody. The combination is equivalent to the single @RestController meta-annotation introduced in Spring 4.0.
Rationale
@RestController is a convenience annotation that combines @Controller and @ResponseBody. Using the two annotations separately is more verbose and may confuse readers about the class’s intent.
// Bad - redundant combination
@Controller
@ResponseBody
public class ApiController {
@GetMapping("/data")
public String getData() { return "data"; }
}
Remediation
Replace the two annotations with @RestController.
// Good - concise and idiomatic
@RestController
public class ApiController {
@GetMapping("/data")
public String getData() { return "data"; }
}