RestController와 Controller 어노테이션 비교
RestController는 @Controller와 @ResponseBody를 합쳐 컨트롤러의 모든 요청에 ResponseBody를 붙여햐 하는 번거러움을 없앤다.
@Controller란?
- @Component 어노테이션 중에서, class path를 스캔할 때 자동적으로 컨트롤러임을 인식할 수 있게 한다.
- request handling method에 보통은 @Controller와 @RequestMapping을 함께 쓴다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Controller
@RequestMapping("books")
public class SimpleBookController {
@GetMapping("/{id}", produces = "application/json")
public @ResponseBody Book getBook(@PathVariable int id) {
// @ResponseBody가 HttpResponse로 반환되는 객체를 자동적으로 직렬화해준다.
return findBookById(id);
}
private Book findBookById(int id) {
// ...
}
}
@RestController란?
위와 달리, @ResponseBody 어노테이션을 매번 사용하지 않아도 된다.
1
2
3
4
5
6
7
8
9
10
11
12
13
@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) {
// ...
}
}