天天看點

Spring MVC中@Controller 和@RestController 注解的差別

原文連結:The Spring @Controller and @RestController Annotations

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.

即:

@RestController

=

@Controller

+

@ResponseBody

*n

例如:

@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) {
        // ...
    }
}
           

等價于:

@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) {
        // ...
    }
}