The Spring @Controller and @RestController Annotations

1. Overview

In this brief tutorial, we’ll discuss the difference between @Controller and @RestController annotations in Spring MVC.

We can use the first annotation for traditional Spring controllers, and it has been part of the framework for a very long time.

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.

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.

4. Conclusion

In this article, we examined the classic and specialized REST controllers available in the Spring Framework.

The complete source code for the examples is available in the GitHub project. This is a Maven project, so it can be imported and used as is.

Related posts:

Java Program to Construct an Expression Tree for an Prefix Expression
Checked and Unchecked Exceptions in Java
Spring 5 Functional Bean Registration
Các chương trình minh họa sử dụng Cấu trúc điều khiển trong Java
Spring RestTemplate Request/Response Logging
Java Program to Represent Graph Using Adjacency Matrix
Java Program to Implement Sorted Singly Linked List
Prevent Brute Force Authentication Attempts with Spring Security
Java Program to Apply Above-Below-on Test to Find the Position of a Point with respect to a Line
How to Delay Code Execution in Java
Multipart Upload with HttpClient 4
Luồng Daemon (Daemon Thread) trong Java
Java Program to Implement RoleList API
Java Program to Implement Dijkstra’s Algorithm using Priority Queue
Java Program to Check whether Graph is a Bipartite using BFS
Java Program to Solve Travelling Salesman Problem for Unweighted Graph
String Joiner trong Java 8
Java Program to Generate N Number of Passwords of Length M Each
Java Program to Implement Skip List
A Guide to ConcurrentMap
Daemon Threads in Java
Java Program to Implement Suffix Array
Bootstrap a Web Application with Spring 5
Jackson Date
Phương thức tham chiếu trong Java 8 – Method References
Java Program to Find the Minimum Element of a Rotated Sorted Array using Binary Search approach
Spring Boot with Multiple SQL Import Files
Class Loaders in Java
Documenting a Spring REST API Using OpenAPI 3.0
Query Entities by Dates and Times with Spring Data JPA
Java Program to Solve Set Cover Problem assuming at max 2 Elements in a Subset
Java Program to Implement Bresenham Line Algorithm