我有一个 spring boot 应用程序,它有一个 spring MVC Controller 。我正在尝试使用 Accept header 对我的 rest api 进行版本控制。
以下是我的 Controller 的样子
RestController
@RequestMapping(value = "/private/")
public class AppleController {
private final AppleService appleService;
public AppleController(AppleService appleService) {
this.appleService = appleService;
}
@GetMapping(value = "apples/{id}", produces = "application/json; v=1.0",
headers = "Accept=application/json; v=1.0")
public ResponseEntity getByappleId(@PathVariable("id") Long appleId) {
System.out.println("version1");
GetByappleIdResponse response = appleService.findByappleId(appleId);
return new ResponseEntity<>(response, HttpStatus.OK);
}
@GetMapping(value = "apples/{id}", produces = "application/json; v=2.0",
headers = "Accept=application/json; v=2.0")
public ResponseEntity getByappleId2(@PathVariable("id") Long appleId) {
System.out.println("version2");
GetByappleIdResponse response = appleService.findByappleId2(appleId);
return new ResponseEntity<>(response, HttpStatus.OK);
}
无论我在调用 API 时在 Accept header 中传递的版本如何,总是调用“getByappleId”方法,因此只返回版本 1 响应。
我的 Controller 有什么问题吗?
请您参考如下方法:
有许多选项可以实现 REST API 的版本控制:
(headers = "Accept=application/vnd.name.v1+json")
(headers = "Accept=application/vnd.name.v2+json")
@GetMapping("apples/v1/{id})"
@GetMapping("apples/v2/{id})
所以你需要决定走哪条路。一些有用的链接: