1. Overview
Spring 4.0 introduced the @RestController annotation in order to simplify the creation of RESTful web services. It’s a convenient annotation that combines @Controller and @ResponseBody, which eliminates the need to annotate every request handling method of the controller class with the @ResponseBody annotation.
The @Controller
annotation indicates that a particular class serves the role of a controller.
What’s special about @Controller?
We cannot switch this annotation with any other like @Service
or @Repository
, even though they look same. The dispatcher scans the classes annotated with @Controller
and detects methods annotated with @RequestMapping
annotations within them. We can use @RequestMapping
on/in only those methods whose classes are annotated with @Controller
and it will NOT work with @Component
, @Service
, @Repository
etc…
2. Spring MVC @Controller
We can annotate classic controllers with the @Controller annotation. This is simply a specialization of the @Component class, which allows us to auto-detect implementation classes through the classpath scanning.
We typically use @Controller in combination with a @RequestMapping annotation for request handling methods.
Let’s see a quick example of the Spring MVC controller:
@Controller @RequestMapping("books") public class SimpleBookController { @GetMapping("/{id}", produces = "application/json") public @ResponseBody Book getBook(@PathVariable int id) { return findBookById(id); } private Book findBookById(int id) { // ... } }
We annotated the request handling method with @ResponseBody. This annotation enables automatic serialization of the return object into the HttpResponse.
3. Spring MVC @RestController
@RestController is a specialized version of the controller. It includes the @Controller and @ResponseBody annotations, and as a result, simplifies the controller implementation:
@RestController @RequestMapping("books-rest") public class SimpleBookRestController { @GetMapping("/{id}", produces = "application/json") public Book getBook(@PathVariable int id) { return findBookById(id); } private Book findBookById(int id) { // ... } }
The controller is annotated with the @RestController annotation; therefore, the @ResponseBody isn’t required.
Every request handling method of the controller class automatically serializes return objects into HttpResponse.