Search code examples
javaspringspring-bootapirequest-mapping

Using a String variable in RequestMapping value


I have the following:

@Value("${apiVersion")
private String apiVersion;

@RequestMapping(value = "/{apiVersion}/service/call", method = RequestMethod.POST)

And I expected the URL to be:

/apiVersion/service/call

But it turns out {foo} accept any value, it doesn't actually use the String.

Is there a way for me to use the String value as part of the URL?

EDIT

The issue is that I have multiple calls that us that value.

@RequestMapping(value = apiVersion + "/call1", method = RequestMethod.POST)

@RequestMapping(value = apiVersion + "/call2", method = RequestMethod.POST)

@RequestMapping(value = apiVersion + "/call3", method = RequestMethod.POST)

etc.

Technically I can declare constants for each one like you suggested, but it doesn't sound optimal. If there is no way to do it then it is fine, I was just wondering if there is.

SOLUTION

Adding general mapping to the controller.

@RequestMapping("${apiVersion}")

Solution

  • If you want to apply it for all methods in a controller declare it on the controller class level:

    @RestController
    @RequestMapping("/test")
    public class MyController { ...
    

    and you do not need to prepend it before method path.

    Otherwise it should be constant so like:

    private static final String FOO = "test";
    

    and prepend it before method path like:

    FOO + "/service/call"