@GetMapping@PostMapping@PutMapping@DeleteMapping@PatchMapping


Spring的復雜性不是來自於它處理的對象,而是來自於自身,不斷演進發展的Spring會帶來 時間 維度上復雜性,比如 SpringMVC以前版本的 *@RequestMapping *
,到了新版本被下面新 注釋 替代,相當於增加的選項:

  • @GetMapping
  • @PostMapping
  • @PutMapping
  • @DeleteMapping
  • @PatchMapping

從命名約定我們可以看到每個注釋都是為了處理各自的傳入請求方法類型,即 *@GetMapping *
用於處理請求方法的 *GET *
類型, *@ PostMapping *
用於處理請求方法的 *POST *
類型等。

如果我們想使用傳統的 *@RequestMapping *
注釋實現URL處理程序,那么它應該是這樣的:

@RequestMapping( value = "/get/{ id }", method = RequestMethod.GET)

新方法可以簡化為:

@GetMapping("/get/{id}")

如何工作?

所有上述注釋都已在內部注釋了 *@RequestMapping *
以及 *方法 *
元素中的相應值。

例如,如果我們查看 *@GetMapping *
注釋的源 代碼 ,我們可以看到它已經通過以下方式使用 *RequestMethod.GET *
進行了注釋:

@Target({ java.lang.annotation.ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented @RequestMapping(method = { RequestMethod.GET }) public @interface GetMapping { // abstract codes } 

所有其他注釋都以相同的方式創建,即 *@PostMapping *
使用 *RequestMethod.POST進行 *
注釋, *@ PutMapping *
使用 *RequestMethod.PUT進行 *
注釋等。

使用方式

下面是結合RestController的簡單使用:

@RestController @RequestMapping("users") public class UserController { @Autowired UserService userService; @GetMapping("/status/check") public String status() { return "working"; } @GetMapping("/{id}") public String getUser(@PathVariable String id) { return "HTTP Get was called"; } @PostMapping public String createUser(@RequestBody UserDetailsRequestModel requestUserDetails) { return "HTTP POST was called"; } @DeleteMapping("/{userId}") public String deleteUser(@PathVariable String userId) { return "HTTP DELETE was called"; } @PutMapping("/{userId}") public String updateUser(@PathVariable String userId, @RequestBody UserDetailsRequestModel requestUserDetails) { return "HTTP PUT was called"; } } 

下面是使用@Controller的代碼:

@Controller public class HomeController { @GetMapping("/") public String homeInit(Model model) { return "home"; } } 

在上面的代碼中,HomeController類充當請求控制器。它的homeInit()方法將處理所有傳入的URI請求"/"。它接受a Model並返回視圖名稱home。使用 配置 的 **視圖 解析 器解析 **
視圖名稱”home“的頁面。

寫法對比

@RequestMapping:

@RequestMapping(value = "/workflow", produces = {"application/json"}, consumes = {"application/json"}, method = RequestMethod.POST) 

@PostMapping如下:

@PostMapping(path = "/members", consumes = "application/json", produces = "application/json") public void addMember(@RequestBody Member member) { //code } 
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM