Which annotation is used to create a RESTful web service in Spring Boot?
Answer:
Explanation:
The @RestController
annotation in Spring Boot is used to create RESTful web services. It is a specialized version of the @Controller
annotation, combining @Controller
and @ResponseBody
annotations. This combination simplifies the creation of RESTful APIs by automatically converting Java objects returned by controller methods into JSON or XML responses, which are then sent back to the client.
Using @RestController
eliminates the need for annotating every method with @ResponseBody
, making the code cleaner and more concise:
@RestController
public class MyController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
}
In this example, the @RestController
annotation ensures that the return value of the sayHello()
method is automatically converted to JSON (or another appropriate format) and sent as the HTTP response body. This annotation is essential for building RESTful APIs in Spring Boot applications, providing a straightforward way to develop web services that communicate with clients over HTTP.