The Spring @Controller and @RestController Annotations – Spring的@Controller和@RestController注解

最后修改: 2018年 4月 2日

1. Overview


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

在这个简短的教程中,我们将讨论Spring MVC中@Controller@RestController注解的区别。

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.

Spring 4.0引入了@RestController注解,以简化RESTful Web服务的创建。这是一个方便的注解,它结合了@Controller@ResponseBody,这样就不需要用@ResponseBody注解来注释控制器类的每个请求处理方法了。

2. Spring MVC @Controller

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.

我们通常将 @Controller@RequestMapping注解结合使用,用于请求处理方法。

Let’s see a quick example of the Spring MVC controller:

让我们看看Spring MVC控制器的一个快速例子。

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

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:


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.