Sobes.tech
Junior — Middle

Explain the purpose of the @ResponseBody annotation in the context of developing RESTful services with Spring

sobes.tech AI

Answer from AI

The @ResponseBody annotation in Spring is used to indicate that the return value of a controller method should be serialized directly into the body of the HTTP response, rather than being interpreted as a view name.

In the context of RESTful services, this means that the object returned by the method is automatically converted into JSON or XML format (depending on the settings) and sent to the client as a response.

Example:

@RestController
public class UserController {

    @GetMapping("/user/{id}")
    @ResponseBody
    public User getUser(@PathVariable Long id) {
        return userService.findById(id);
    }
}

Here, @ResponseBody ensures that the User object is converted into JSON and sent in the HTTP response, which is standard behavior for REST APIs.