我有一个 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 的版本控制:

  • 在评论方法中建议手动路由您的请求;
  • 将版本作为 Accept header 值的一部分,例如:
    (headers = "Accept=application/vnd.name.v1+json")(headers = "Accept=application/vnd.name.v2+json")
  • 将版本作为映射的一部分:
    @GetMapping("apples/v1/{id})"@GetMapping("apples/v2/{id})

  • 所以你需要决定走哪条路。一些有用的链接:
  • Versioning a REST API
  • Best practices for API versioning?

  • 评论关闭
    IT干货网

    微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!