liveBook · Manning

Restcontroller annotation

As explained in Spring Start Here, Second Edition

The @RestController annotation marks a Spring MVC controller whose actions return response data directly and are treated as REST endpoints.

@RestController marks a class whose controller actions return data directly in HTTP responses. It combines @Controller and @ResponseBody, so you do not need to repeat @ResponseBody on every action. section 10.2

Listing 10.3 Using the @RestController annotation to avoid code duplication.
@RestController    #A
public class HelloController {
 
  @GetMapping("/hello")
  public String hello() {
    return "Hello!";
  }
 
  @GetMapping("/ciao")
  public String ciao() {
    return "Ciao!";
  }
}

A HelloController uses @RestController once for its /hello and /ciao actions, replacing repeated @ResponseBody annotations. section 10.2

Without @RestController or @ResponseBody, Spring’s dispatcher servlet assumes an action returns a view name and looks for that view. section 10.6

How Spring Start Here, Second Edition covers it

How deep it goes
Defines the annotation as a combination of @Controller and @ResponseBody, without detailing framework internals.
Examples
Uses a HelloController with /hello and /ciao actions returning greeting strings.
What you can do after
Build it from scratch by marking a controller class with @RestController instead of repeating @ResponseBody on its actions.
How it connects
Connects @Controller and @ResponseBody with Spring MVC REST endpoints.

Also explained in

Compare how 3 books explain restcontroller annotation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Start Here, Second Edition. The section links point to the parts of the book it draws on.