@GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping là shortcut (composed annotation) của @RequestMapping(method = ...), có từ Spring 4.3:
@GetMapping("/users")=@RequestMapping(value = "/users", method = RequestMethod.GET).
Khác biệt đáng nhớ:
- @RequestMapping đặt được ở class level làm base path chung cho cả controller; các shortcut chỉ đặt được trên method.
- @RequestMapping không khai method → match mọi HTTP method — thường là bug ngầm (endpoint GET bỗng nhận cả POST).
- @RequestMapping còn các attribute ít dùng: consumes, produces, params, headers — shortcut cũng có đủ.
Best practice: @RequestMapping("/api/users") ở class cho base path + shortcut ở method — code gọn, HTTP verb đọc thấy ngay, không mở endpoint ngoài ý muốn.
@GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping are shortcuts (composed annotations) for @RequestMapping(method = ...), available since Spring 4.3:
@GetMapping("/users")=@RequestMapping(value = "/users", method = RequestMethod.GET).
Differences worth remembering:
- @RequestMapping can sit at class level as the controller-wide base path; the shortcuts work only on methods.
- @RequestMapping without a method matches every HTTP method — usually a silent bug (a GET endpoint suddenly accepting POST too).
- @RequestMapping also has the lesser-used attributes consumes, produces, params, headers — the shortcuts support them as well.
Best practice: @RequestMapping("/api/users") on the class for the base path + shortcuts on methods — concise code, the HTTP verb is instantly readable, and no endpoint is opened unintentionally.