简体   繁体   中英

Api versioning in spring boot

I am trying to do the API versioning based on the below scenario. I have a package called V1 & V2 , each has its own controller with Route mapping

@RequestMapping(path = "api/v${ApiVersion}/product")
public class ProductController {}

In the application.yml I have the below configuration,

ApiVersion: 1

spring:
  profiles:
    active: dev
server:
  port: 8083

ApiVersion: 1

在此处输入图像描述

What I am trying to do is:

  1. If the URL has V1 (ApiVersion: 1) then it should route to V1 controller http://192.168.1.101:8083/api/v1/product
  2. If the URL has V2 (ApiVersion: 2) then it should route to V2 controller 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:

@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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM