[英]Spring rest controller - different values for same header
I have a Spring REST controller and two separate GetMappings with the same value but each accepting a different header value for the same header (ie, one GET method for v1 and one GET method for v2).
@GetMapping(value = "/{id}", headers = { "Accept-version=v1"})
public UserV1 findByIdV1(@PathVariable long id) {
return ...;
}
@GetMapping(value = "/{id}", headers = { "Accept-version=v2"})
public UserV1 findByIdV2(@PathVariable long id) {
return ...;
}
如果实现没有从一个版本更改为另一个版本,那么拥有一个可以接受 header 值的单一方法的最佳方法是什么?
理想情况下,该解决方案将允许我为具有不同实现的不同版本使用不同的方法,以便能够使用 OpenAPI 正确记录这些。 类似于以下内容:
@GetMapping(value = "/{id}", headers = { "Accept-version=v1 OR Accept-version=v2"})
public UserV1 findByIdV1(@PathVariable long id) {
return ...;
}
// Different response, thus need different method to be able to document this.
@GetMapping(value = "/{id}", headers = { "Accept-version=v3"})
public UserV3 findByIdV2(@PathVariable long id) {
return ...;
}
您可以使用@RequestHeader
将方法内部的header 信息作为参数传递:
@GetMapping(value = "/{id}")
public UserV1 findByIdV2(
@PathVariable long id,
@RequestHeader("Accept-version") String acceptVersion
) {
// make a decision based on acceptVersion
return ...;
}
您可以通过Accept
header 来做到这一点。
A great example is the Github API: https://docs.github.com/en/free-pro-team@latest/rest/overview/media-types
Spring 实现:
@GetMapping(value = "/{id}", headers = {"Accept=application/vnd.api.v1+json", "Accept=application/vnd.api.v2+json"})
public UserV1 findByIdV1(@PathVariable long id) {
return ...;
}
@GetMapping(value = "/{id}", headers = "Accept=application/vnd.api.v3+json")
public UserV3 findByIdV2(@PathVariable long id) {
return ...;
}
注意:您可以在自己的域名 vnd 上更改api
部分vnd.
部分由rfc4288-3.2规定,用于区分标准媒体类型和自定义媒体类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.