What is the use of @RestController in Spring MVC?
Answer:
Explanation:
The @RestController
annotation in Spring MVC is a specialized version of the @Controller
annotation. It combines the functionality of the @Controller
and @ResponseBody
annotations, making it easier to create RESTful web services.
When you annotate a class with @RestController
, all the methods within that class automatically have the @ResponseBody
behavior, meaning the return values are written directly to the HTTP response body. This eliminates the need to annotate each method with @ResponseBody
individually.
For example:
@RestController
public class MyRestController {
@GetMapping("/api/greet")
public String greet() {
return "Hello, RESTful World!";
}
}
In this example, the greet()
method returns a plain text string, “Hello, RESTful World!”. The @RestController
annotation ensures that this string is written directly to the HTTP response body without needing to explicitly use the @ResponseBody
annotation.
The @RestController
annotation simplifies the creation of RESTful APIs in Spring MVC, making it a key feature when building modern web services.