Spring Framework FAQ: Top Questions
26. What is @RestController in Spring and how is it different from @Controller?
@RestController
is a convenience annotation that combines @Controller
and @ResponseBody
. It is used to build RESTful web services by returning data directly as JSON or XML.
📘 Key Differences:
@Controller
: Used for rendering views (e.g., JSP, Thymeleaf).@RestController
: Returns objects directly in HTTP response body.
📥 Example:
@RestController
public class ApiController {
@GetMapping("/api/greet")
public String greet() {
return "Hello, API!";
}
}
🏆 Expected Output:
Returns plain text or JSON response: "Hello, API!"
🛠️ Use Cases:
- Building RESTful web services.
- Creating JSON APIs for SPAs or mobile apps.