Difference Between @Controller,@RestController admin, January 31, 2025January 31, 2025 In Spring Framework, both @Controller and @RestController are used to define controllers, but they serve different purposes. Here’s the key difference: 1. @Controller It is used in Spring MVC to define a web controller that handles HTTP requests. Typically used for web pages where a view (like JSP, Thymeleaf) is returned. Requires @ResponseBody on methods that return JSON or XML instead of a view. Example: @Controllerpublic class MyController { @GetMapping("/home") public String homePage() { return "home"; // Returns the view name (e.g., home.html or home.jsp) } @GetMapping("/data") @ResponseBody public String getData() { return "Hello, World!"; // Returns raw response (without a view) }} 2. @RestController Introduced in Spring 4.0 as a specialization of @Controller. It is a combination of @Controller and @ResponseBody, meaning all methods return data directly (usually JSON or XML). No need to use @ResponseBody on each method. Example: @RestControllerpublic class MyRestController { @GetMapping("/greet") public String greet() { return "Hello, World!"; // Returns raw response (e.g., JSON or plain text) } @GetMapping("/user") public Map<String, String> getUser() { Map<String, String> user = new HashMap<>(); user.put("name", "John"); user.put("role", "Admin"); return user; // Returns JSON response }} Key Differences: Feature@Controller@RestControllerView ResolutionReturns a view (e.g., JSP, Thymeleaf)Returns data (JSON/XML)Implicit @ResponseBodyNo (must be added manually)Yes (applied to all methods)Use CaseWeb applications (MVC)RESTful APIs When to Use What? Use @Controller if you are building a traditional web application with views. Use @RestController if you are developing a REST API that returns JSON/XML. Spring Boot