0

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

enter image description here

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?

San Jaisy
  • 15,327
  • 34
  • 171
  • 290
  • Does this answer your question? [Spring: define @RequestMapping value in a properties file](https://stackoverflow.com/questions/31904444/spring-define-requestmapping-value-in-a-properties-file) – Malathi Jul 17 '20 at 03:27
  • 1
    What are you trying to achieve with having the version in your properties file? You already hardcoded the version in your package number you might as well hardcode it for the path in each controller. Both controllers would point to v1 if you populate the path using the variable from properties file like in your example. – dozerman Jul 17 '20 at 05:25
  • @dozerman - Yes you are 100% correct. My requirement is when I use version - V1 in URL it should take the controller from V1 package, vice versa for V2. – San Jaisy Jul 17 '20 at 05:41
  • 1
    @SanJaisy so you don't need the version in your properties. Just build two hardcoded mappings (one each for v1 and v2) and each request will be processed according to their version. – dozerman Jul 17 '20 at 21:09

1 Answers1

1

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 {

}

Now, 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 version 1 service
      }
      else if(apiVersion == 2) {
         //invoke version 2 service
      }
      else{
       //throw exception for invalid version
      }
         
    }
}

You don't need to set anything in application.properties.

ikaerom
  • 538
  • 5
  • 27
Tayyab Razaq
  • 348
  • 2
  • 11
  • I have two controller, but they are in different package. But the RequestMapping I can't hardcode on the controller I need to filter from application.properties file. – San Jaisy Jul 17 '20 at 06:57