1

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}")
A.J
  • 1,140
  • 5
  • 23
  • 58

2 Answers2

2

If you just want to predefine the path in Java just do

@RequestMapping(value = foo + "/service/call", method = RequestMethod.POST)

PathVariables in SpringMvc are meant to be a placeholder for endpoints like in the following

@GetMapping(value = "/books/{id}")
public String displayBook(@PathVariable id) { ... }
J Asgarov
  • 2,526
  • 1
  • 8
  • 18
  • I tried that earlier, but I am getting `element value must be a constant expression` error. – A.J Jul 17 '20 at 16:11
  • then define it as a final static path in class: private static final String FOO_PATH = "foo/service/call"; afterwards you can use it in the @RequestMapping(value = FOO_PATH) – J Asgarov Jul 17 '20 at 16:15
  • Edited my question to address your idea. – A.J Jul 17 '20 at 16:21
2

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"
pirho
  • 11,565
  • 12
  • 43
  • 70
  • I am reading the value from `application.properties` file, can I still use it like you suggested? I edited my question to show the actual declaration. – A.J Jul 17 '20 at 16:25
  • I am afraid that unfortunately not. All values in annotations must be constants and defined at the compile time. I've seen some are complex stuff to edit annotations at runtime but projects I've been just do not use app.props but a file that has java constants for these paths. Should not be a problem that way either, in another file than app.props. – pirho Jul 17 '20 at 16:29
  • `@RequestMapping("${apiVersion}")` this worked actually. – A.J Jul 17 '20 at 16:33
  • Ok, I learned something new :) Seems that Spring can translate that placeholder at runtime, good, – pirho Jul 17 '20 at 16:35