Java and Spring Level 1 This level · 75 of 105
Easy java spring

Difference between @RestController and @Controller internally?

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.

Could you say this in an interview?

The declaration says it all:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {

RestController.java L45-L50

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, RequestResponseBodyMethodProcessor handles it. It chooses an HttpMessageConverter based on the return type and the request's Accept header, and writes the body. No view is involved.
  • Otherwise, a String return value is a view name, and a ModelAndView or Model is used for rendering by a ViewResolver.

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)
  1. @RestController Javadocdocs.spring.io
  2. Spring Framework reference: @ResponseBodydocs.spring.io
  3. Spring Framework reference: Return valuesdocs.spring.io
Previous
Next