Sobes.tech
Junior — Middle

What role does the @RestController annotation play in developing REST API with Spring?

sobes.tech AI

Answer from AI

The @RestController annotation in Spring combines @Controller and @ResponseBody. It indicates that the class is a controller that handles HTTP requests and returns data directly in the response body, usually in JSON or XML format.

This simplifies REST API development, as there's no need to specify @ResponseBody for each method separately.

Example:

@RestController
public class UserController {

    @GetMapping("/users/{id}")
    public User getUser(@PathVariable Long id) {
        // Returns a User object, which is automatically serialized to JSON
        return userService.findById(id);
    }
}