1.概述
Spring 4.3,添加了一些非常酷的方法级别的组合注释(composed annotation)。组合注解可以更好地表达的语义。
在本文中,我们将介绍@RequestMapping
相关组合注解以及如何使用它们。
2.新注解
在Spring 4.3 之前,如果我们想使用的@RequestMapping
注解实现URL映射处理,可能会是这样的:
@RequestMapping(value = "/composed/{id}", method = RequestMethod.GET)
而使用新的组合注解可以是这样:
@GetMapping("/composed/{id}")
Spring MVC内置了五种关于@RequestMapping
的组合注解,用于处理不同类型的HTTP请求:
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
从命名中,我们就可以看到每个注释都在处理各自的HTTP请求方法类型,
也就是@GetMapping
用于处理GET类型的请求方法,@PostMapping
用于处理POST类型的请求方法。。。
3.原理
以上所有组合注解都在内部使用@RequestMapping
并且对要处理的HTTP方法类型进行了设定。
我们来看一下@GetMapping
的源代码:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = RequestMethod.GET)
public @interface GetMapping {
/**
* Alias for {@link RequestMapping#name}.
*/
@AliasFor(annotation = RequestMapping.class)
String name() default "";
}
我们可以看到它已经通过RequestMethod.GET
设置了@RequestMapping
处理的HTTP方法类型。
其他的注解我们就不看。如果你想看@GetMapping
的完整源代码,可以去这里。
4. 实战
我们分别来看一下关于@RequestMapping
的组合注解。
4. 1 @GetMapping
下面是分别使用了@GetMapping
和@RequestMapping
。他们是等效的。
- @GetMapping
@GetMapping("/get/{id}")
@ResponseBody
public String getById(@PathVariable String id) {
return "GET Response";
}
- @RequestMapping
@RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
@ResponseBody
public String getById(@PathVariable String id) {
return "GET Response : " + id;
}
4.2 @PostMapping
下面两种写法是等效的。
- @PostMapping
@PostMapping("/post")
@ResponseBody
public String post() {
return "POST Response ";
}
- @RequestMapping
@RequestMapping(value = "/post", method = RequestMethod.POST)
@ResponseBody
public String post() {
return "POST Response ";
}
4.3 @PutMapping
- @PutMapping
@PostMapping("/put")
@ResponseBody
public String put() {
return "PUT Response ";
}
- @RequestMapping
@RequestMapping(value = "/put", method = RequestMethod.PUT)
@ResponseBody
public String put() {
return "PUT Response ";
}
4.4 @DeleteMapping
- @DeleteMapping
@PostMapping("/delete")
@ResponseBody
public String delete() {
return "DELETE Response ";
}
- @RequestMapping
@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
@ResponseBody
public String delete() {
return "DELETE Response ";
}
4.5 @PatchMapping
- @PatchMapping
@PatchMapping("/patch")
@ResponseBody
public String patch() {
return "PATCH Response";
}
- @RequestMapping
@RequestMapping(value = "/patch", method = RequestMethod.PATCH)
@ResponseBody
public String patch() {
return "PATCH Response";
}
因为代码比较简单,我们就不测试。
5. 结论
在本文中,我们对使用传统Spring MVC框架进行快速Web开发的@RequestMapping
组合注解行了快速介绍。
我们可以利用这些组合注解行来编写干净的易读的代码。
与往常一样,可以在GitHub上找到示例实现。