Search code examples
javaspring-bootrequest-mapping

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


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!


Solution

  • 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.