[英]Api versioning in spring boot
I am trying to do the API versioning based on the below scenario.我正在尝试根据以下场景进行 API 版本控制。 I have a package called V1 & V2 , each has its own controller with Route mapping
我有一个名为V1 & V2的 package ,每个都有自己的 controller 和路由映射
@RequestMapping(path = "api/v${ApiVersion}/product")
public class ProductController {}
In the application.yml I have the below configuration,在 application.yml 我有以下配置,
ApiVersion: 1 API版本:1
spring:
profiles:
active: dev
server:
port: 8083
ApiVersion: 1
What I am trying to do is:我想做的是:
http://192.168.1.101:8083/api/v1/product
http://192.168.1.101:8083/api/v1/product
http://192.168.1.101:8083/api/v2/product
http://192.168.1.101:8083/api/v2/product
Is it possible to achieve?有没有可能实现?
Ideally, you should have different controllers for each version and you invoke services accordingly.理想情况下,每个版本应该有不同的控制器,并相应地调用服务。 For example:
例如:
@RestController
@RequestMapping(path = "api/v1/product")
public class ProductController {
}
@RestController
@RequestMapping(path = "api/v2/product")
public class ProductController {
}
But if you want to keep one controller, you can do like this:但是如果你想保留一个 controller,你可以这样做:
@RestController
@RequestMapping(path = "api/v{apiVersion}/product")
public class ProductController {
@GetMapping("{id}")
public Product getById(@PathVariable Integer apiVersion,
@PathVariable Integer id) {
if(apiVersion == 1) {
//invoke bersion 1 service
}
else if(apiVersion == 2) {
//invoke bersion 2 service
}
else{
//throw exception for invalid version
}
}
}
You don't need to set anything in application.properties
.您无需在
application.properties
中设置任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.