@RequestMapping與@GetMapping和@PostMapping等新註釋
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 }