What is the difference between @Controller and @RestController?
Quick Answer
@Controller marks a class as a Spring MVC web controller whose handler methods, by default, return a logical view name to be resolved and rendered (e.g., a Thymeleaf template) — returning a raw object requires an explicit @ResponseBody on the method. @RestController is a convenience meta-annotation combining @Controller and @ResponseBody, so every handler method's return value is written directly to the HTTP response body (typically serialized to JSON), which is why it's the default choice for building REST APIs.
Detailed Answer
Both mark a class as a Spring MVC controller, discovered via component scanning, but they differ in how a handler method's return value is treated:
@Controller — return values are treated as logical view names by default, resolved by a ViewResolver into an actual view (e.g., a Thymeleaf/JSP template) to render:
@Controller
class HomeController {
@GetMapping("/home")
String home(Model model) {
model.addAttribute("message", "Welcome");
return "home"; // resolved to a "home" view template, not returned as raw text
}
}
To return raw data (e.g., JSON) from an @Controller, you must explicitly annotate the method with @ResponseBody:
@Controller
class ApiController {
@GetMapping("/api/status")
@ResponseBody
Map<String, String> status() { return Map.of("status", "ok"); } // written directly as JSON
}
@RestController is a meta-annotation combining @Controller and @ResponseBody at the class level — every handler method's return value is automatically serialized (typically to JSON via Jackson) and written straight to the response body, with no view resolution involved:
@RestController
class ApiController {
@GetMapping("/api/status")
Map<String, String> status() { return Map.of("status", "ok"); } // JSON body, no @ResponseBody needed
}
Rule of thumb: use @RestController for REST/JSON APIs (the vast majority of modern Spring Boot backends); use @Controller specifically when a controller renders server-side views, or has a genuine mix of both view-rendering and data-returning endpoints.