Junior — Middle
What is the role of the RestController annotation in developing RESTful web services?
sobes.tech AI
Answer from AI
The @RestController annotation in Spring is used for creating RESTful web services. It combines the functionality of @Controller and @ResponseBody, meaning that the controller methods automatically serialize the returned objects into JSON (or another format) and send them in the HTTP response without the need to manually write conversion code.
This simplifies API development, as it allows for quickly creating controllers that handle HTTP requests and return data in a client-friendly format (such as for web or mobile applications).
Example:
@RestController
public class UserController {
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
// logic to get user
return userService.findById(id);
}
}
Here, the getUser method returns a User object, which is automatically converted to JSON and sent to the client.