In Spring, @ResponseBody marks a handler method (or a whole controller) so that its return value is serialised into the HTTP response body rather than resolved as a view. It is how a Spring MVC controller returns JSON, plain text or other data to a client such as a browser script or mobile app.
This article focuses on where the annotation applies, how it works with exception handlers, and how it compares with ResponseEntity.
The annotation has two valid targets: a method or a type.
@RestController gives you, since it is meta-annotated with @Controller and @ResponseBody.The /users handler returns a view name for the template engine. The /api/users handler is annotated, so Spring serialises the list.
Spring MVC uses the registered HttpMessageConverter beans. With spring-boot-starter-web, JSON support is auto-configured, so a List<UserDto> is written as a JSON array and the response gets Content-Type: application/json.
For String return values, the string converter is used and the content type defaults to text/plain (or to what the Accept header allows). Use produces on the mapping annotation to fix the type.
A common use is an @ExceptionHandler that returns a structured error. In a @RestControllerAdvice, @ResponseBody is already implied. In a plain @ControllerAdvice you add it yourself.
Without @ResponseStatus, the response would be 200 even though it carries an error. For new APIs, consider the ProblemDetail type (RFC 9457 problem details), which Spring supports directly as a return value from exception handlers.
Both write a body. The difference is how much of the response you control.
| Aspect | @ResponseBody | ResponseEntity<T> |
|---|---|---|
| Body | Return value | Entity body |
| Status | 200 or @ResponseStatus | Chosen at runtime |
| Headers | Set through HttpServletResponse or not at all | Built fluently |
| Needs annotation | Yes (unless @RestController) | No |
Use ResponseEntity when the status or headers vary by request, and plain @ResponseBody (or @RestController) when a 200 with a body is always right.
@Controller: Spring then looks for a view named after the returned object's string form and you get a template error or 404.@RequestBody, which reads the incoming body.No. @RestController is a class-level shortcut that adds @ResponseBody to every method, plus @Controller.
Yes, with @Controller: annotate only the JSON handlers with @ResponseBody.
Return byte[], a Resource or a StreamingResponseBody and set produces or the Content-Type header through ResponseEntity.
Spring finds the annotation on the method, its class, or inherited declarations, but declaring it on the concrete controller is the clearest.
@ResponseBody makes a Spring MVC method write its return value to the response body through a message converter. Apply it to methods or classes, rely on @RestController for API controllers, add @ResponseStatus or return ResponseEntity to control status codes, and return DTOs rather than persistence entities.