Configure the root path of a RequestMapping to be reusable in Spring Boot

88 views Asked by At

I'd like to centralize the root path of some of our endpoints in order to avoid having to write every url for the different endpoints.

I have something similar to this:

@RestController
@RequestMapping(value = {"/api/en/myproject", "/api/de/myproject"})
public ResponseEntity<?> myProject() {
    ...
}
    
@RestController
@RequestMapping(value = {"/api/en/myproject/subproject", "/api/de/myproject/subproject"})
public ResponseEntity<?> mySubProject() {
    ...
}

I've tried creating a static string[] but the compiler doesn't allow non-constant attributes there.

What I'd like to have is, but I am not sure if a workaround could be achieved:

@RestController
@RequestMapping(value = {getProjectPath()})
public ResponseEntity<?> myProject() {
    ...
}
    
@RestController
@RequestMapping(value = {getSubprojectPath()})
public ResponseEntity<?> mySubProject() {
    ...
}

That way I could append /subproject to the first array of strings and if some path changes in the future I only need to look at one place.

Any ideas?

Thanks!

2

There are 2 answers

0
Oscar On BEST ANSWER

One solution would be to define request mapping value in application properties file and updated it on runtime or directly in file as you want:

@RequestMapping("/${project.path}")
public ResponseEntity<?> myProject() {
  //...
}

@RequestMapping("/${subProject.path}")
public ResponseEntity<?> mySubProject() {
  //...
}

in application.properties file:

project.path=/project/path
subProject.path=subProject/path

With this, you can also set these properties using env variables if you want.

Hope it's could be helpful.

0
Nikolai  Shevchenko On

In your particular case you can use parametrized URL and just ignore language parameter

@RequestMapping(value = "/api/{lang}/myproject")
public ResponseEntity<?> myProject(@PathVariable("lang") String language) {
    ...
}

@RequestMapping(value = "/api/{lang}/myproject/subproject")
public ResponseEntity<?> mySubProject(@PathVariable("lang") String language) {
    ...
}

P.S. @RestController should be used for classes only, not for methods