1. Overview
In this quick tutorial, we’ll discuss the difference between @Controller and @RestController annotations in Spring MVC.
The first annotation is used for traditional Spring controllers and has been part of the framework for a very long time.
The @RestController annotation was introduced in Spring 4.0 to simplify the creation of RESTful web services. It’s a convenience annotation that combines @Controller and @ResponseBody – which eliminates the need to annotate every request handling method of the controller class with the @ResponseBody annotation.
2. Spring MVC @Controller
Classic controllers can be annotated with the @Controller annotation. This is simply a specialization of the @Component class and allows implementation classes to be autodetected through the classpath scanning.
@Controller is typically used in combination with a @RequestMapping annotation used on 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) { // ... } }
The request handling method is annotated 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.
4. Conclusion
In this article, we saw the classic and specialized REST controllers available in the Spring Framework.
The complete source code for the example is available in the GitHub project; this is a Maven project, so it can be imported and used as-is.