The 30 second answer
@RestController combines @Controller and @ResponseBody. In Spring MVC, that means ordinary return values are handled as response content, using an HttpMessageConverter, often Jackson for JSON. With a plain @Controller, a returned String is normally a view name for a ViewResolver, unless I add @ResponseBody. Both annotations use the same request-mapping and argument-resolution infrastructure. The main difference is how Spring interprets the handler's return value, not how it routes the request.
The declaration says it all:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {So both are detected the same way: @Controller is a @Component, and RequestMappingHandlerMapping registers their @RequestMapping methods.
The difference is in return value handling. RequestMappingHandlerAdapter picks a HandlerMethodReturnValueHandler for each return value:
- If the method or class has
@ResponseBody,RequestResponseBodyMethodProcessorhandles it. It chooses anHttpMessageConverterbased on the return type and the request'sAcceptheader, and writes the body. No view is involved. - Otherwise, a
Stringreturn value is a view name, and aModelAndVieworModelis used for rendering by aViewResolver.
Example:
@Controller
class PageController {
@GetMapping("/orders")
String orders(Model model) {
model.addAttribute("orders", service.findAll());
return "orders"; // renders templates/orders.html
}
}
@RestController
class OrderApi {
@GetMapping("/api/orders")
List<OrderDto> orders() {
return service.findAll(); // JSON array in the body
}
}Mixing: a @Controller can still have one JSON method by putting @ResponseBody on that method. ResponseEntity<T> works in both and also lets you set status and headers.
Common bug: using @Controller for an API and returning an object. Spring tries to resolve a view and you get a 404 or "circular view path" error instead of JSON.
Sources (3)
- @RestController Javadocdocs.spring.io
- Spring Framework reference: @ResponseBodydocs.spring.io
- Spring Framework reference: Return valuesdocs.spring.io