Junior — Middle
Have you used the RestController annotation when developing RESTful APIs in Spring?
sobes.tech AI
Answer from AI
Yes, the @RestController annotation in Spring is used for creating RESTful web services. It combines @Controller and @ResponseBody, meaning that the controller methods automatically serialize the returned objects into JSON or XML and send them in the HTTP response.
Example of usage:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@GetMapping("/users")
public List<String> getUsers() {
return List.of("Alice", "Bob", "Charlie");
}
}
In this example, when a GET request is made to /users, the client receives a JSON array with user names. @RestController simplifies API creation by eliminating the need to manually write code for converting objects into JSON.