How to set a context root for all @RestController in Spring Web MVC?
Asked Answered
T

2

6

I'm looking to define /api as the root context for all my @RestControllers and don't want to specify it for each of them.

For instance, I would like to write @RestController("/clients") instead of @RestController("/api/clients") and make my request mappings available at /api/clients but have my static resources (in /main/resources/static) still served at /**.

So, setting server.servlet.contextPath=/api in application.properties is not a solution for my use case because the static resources will be served at /api, which I don't want.

In brief, I would like to have the same feature as JAX-RS @ApplicationPath("/api") in Spring Web MVC, is this possible?

Twoway answered 13/11, 2017 at 13:13 Comment(0)
T
1

One of the possible solution(work around) is to use Parent Class with mapping

@RequestMapping(path="/api")
abstract class BaseController{
    ....
}

Other controllers can extend it

class OtherController extends BaseController {
  @RequestMapping(path="/clients")
  public ....clients(....){
   .....
  }
}

Please note that @RequestMapping will get overridden if you place it on top of any child class. Like explained here and here

Tricycle answered 13/11, 2017 at 14:43 Comment(0)
P
0

Set the context root you want by using spring.mvc.servlet.path config into your application.properties.

e.g:

spring.mvc.servlet.path=/api/v1
Pamella answered 3/7, 2019 at 13:2 Comment(1)
not working with webfluxLissotrichous

© 2022 - 2024 — McMap. All rights reserved.