具有相同路径但具有不同 @RequestParam 值的多个端点

Multiple endpoints with the same path but with different @RequestParam values

我有一个 API 路径 GET /users/copy。我可以有两个 APIs 具有相同的 /users/type 路径但使用以下构造具有不同的 RequestParams 集:

@GetMapping(value = "/users/copy", params = {"type"})
public ResponseEntity<UserDto> copyUserWithType(@RequestParam UserTypeEnum type) {
    ...
}

@GetMapping(value = "/users/copy", params = {"origin"})
public ResponseEntity<UserDto> copyUserWithOrigin(@RequestParam UserOriginEnum origin) {
    ...
}

BUT 如果我需要为不同的用户类型设置不同的 API(比如 type = OLDtype = NEW),是有没有办法让他们仍然拥有相同的 GET /users/copy 路径?

可能是这样的:

@GetMapping(value = "/users/copy", params = {"type=OLD"})
public ResponseEntity<UserDto> copyUserWithTypeOld(@RequestParam UserTypeEnum type) {
    ...
}  

@GetMapping(value = "/users/copy", params = {"type=NEW"})
public ResponseEntity<UserDto> copyUserWithTypeNew(@RequestParam UserTypeEnum type) {
    ...
}

其实答案就在问题里

为了让不同的 API 端点具有相同的路径和相同的 @ReuqestParam 集,但具有不同的 @ReuqestParam 值,您需要指定 params 属性:

@GetMapping(value = "/users/copy", params = {"type=OLD"})
public ResponseEntity<UserDto> copyUserWithTypeOld(@RequestParam UserTypeEnum type) {
    ...
}  

@GetMapping(value = "/users/copy", params = {"type=NEW"})
public ResponseEntity<UserDto> copyUserWithTypeNew(@RequestParam UserTypeEnum type) {
    ...
}