3

We have some already developed REST APIs in SpringBoot.

Now we want to prepend some text (version of API eg /v1/) to all the @RequestMapping.

Is there any way of doing this except prepending /v1/ to every @RequestMapping


example: Current RequestMapping /employess and /cars/1/driver

Need to build like this /v1/employess and /v1/cars/1/driver

Mehraj Malik
  • 14,872
  • 15
  • 58
  • 85

3 Answers3

3

You can use such property in your application.properties file:

server.servlet.contextPath=/v1

or you can have a base controller class and extend it with all your controller classes

@RestController
@RequestMapping(value = "${rest.api.version}")
public class MyAbstractController {
}

and store rest.api.version in your application.properties file.

Pijotrek
  • 2,821
  • 1
  • 18
  • 32
0

You could do it in at least 2 ways.

Option 1: extend AbstractAnnotationConfigDispatcherServletInitializer as below:

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {


    @Override
    protected String[] getServletMappings() {
        return new String[] { "/v1/*" };
    }

}

Option 2: add a request mapping on class level on the controllers you want the version prepended as below

@RestController
@RequestMapping("/v1")
public class Controller {
}

I would go for option 1.

martidis
  • 2,897
  • 1
  • 11
  • 13
0

If you want to append every request with "/v1", You can do so by using @RequestMapping annotation at the class level, in this way all the incoming calls(which has "/v1" in it) will land in your controller

@RestController
@RequestMapping("/v1")
public class YourController {
}
chetan007
  • 11
  • 4
  • I asked for All Controller, not just one controller! – Mehraj Malik Jan 21 '19 at 10:39
  • Found the solution : https://mhdevelopment.wordpress.com/2016/10/03/spring-restcontroller-specific-basepath/ – chetan007 Jan 21 '19 at 11:52
  • possible duplicate of this question : https://stackoverflow.com/questions/34801351/how-to-configure-a-default-restcontroller-uri-prefix-for-all-controllers/39716758#39716758 – chetan007 Jan 21 '19 at 11:52