@RequestMapping與@GetMapping和@PostMapping等新注釋
Spring的復(fù)雜性不是來自于它處理的對象,而是來自于自身,不斷演進發(fā)展的Spring會帶來時間維度上復(fù)雜性,比如SpringMVC以前版本的@RequestMapping,到了新版本被下面新注釋替代,相當于增加的選項:
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
從命名約定我們可以看到每個注釋都是為了處理各自的傳入請求方法類型,即@GetMapping用于處理請求方法的GET類型,@ PostMapping用于處理請求方法的POST類型等。
如果我們想使用傳統(tǒng)的@RequestMapping注釋實現(xiàn)URL處理程序,那么它應(yīng)該是這樣的:
@RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
新方法可以簡化為:
@GetMapping("/get/{id}")
如何工作?
所有上述注釋都已在內(nèi)部注釋了@RequestMapping以及方法元素中的相應(yīng)值。
例如,如果我們查看@GetMapping注釋的源代碼,我們可以看到它已經(jīng)通過以下方式使用RequestMethod.GET進行了注釋:
@Target({ java.lang.annotation.ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = { RequestMethod.GET })
public @interface GetMapping {
// abstract codes
}
所有其他注釋都以相同的方式創(chuàng)建,即@PostMapping使用RequestMethod.POST進行注釋,@ PutMapping使用RequestMethod.PUT進行注釋等。
使用方式
下面是結(jié)合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
}