Configure path prefixes for different WebAPIs in one Spring Boot App

Viewed 137

I have a Spring Boot App with several WebAPIs. How can I configure the path prefix of each WebAPI differently via application properties?

For example I have a UserRestController and a StarShipRestController. Both are part of different WebAPIs, but served by the same Spring Boot App. The RestControllers should only feature the last part of the URL to the resource. The path prefix should not be part of the RestController:

@RestController
@RequestMapping("users")
class UserRestController  {

    // methods...
}

and

@RestController
@RequestMapping("starships")
class StarShipRestController  {

    // methods...
}

The concrete path prefixes are in application.properties:

api.user.pathPrefix=/api/v1
api.starship.pathPrefix=/universe

The question is how to apply the path prefixes to the RestControllers?

If there was only one WebAPI in the Spring Boot App, I could use a WebMvcConfigurer. But that doesn't work because I have several WebAPIs.

@Configuration
public class WebMvcConfig implements WebMvcConfigurer  {

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.addPathPrefix("api", HandlerTypePredicate.forAnnotation(RestController.class));
    }
}
1 Answers

You can only have one context-path for a single Spring-Boot application (which can be configured using server.servlet.context-path). This means what you are asking is not possible.

The only way to achieve it is by changing the @RequestMapping annotations in your Controllers to include the full path that you want.

@RestController
@RequestMapping("/api/v1/users")
class UserRestController  {

    // methods...
}
@RestController
@RequestMapping("/universe/starships")
class StarShipRestController  {

    // methods...
}

To my knowledge, there is no other way.

Considering your request, I ask myself if you shouldn't have two different Spring-Boot applications instead of just one.

Related