How to configure a default @RestController URI prefix for all controllers?

ghz 1years ago ⋅ 8385 views

Question

I know you can set the server.contextPath in application.properties to change the root context.

Also, I can add an additional context in the application config for Spring Boot like the following example (in Groovy) to add an "/api" to the URL mappings of the root context:

@Bean
ServletRegistrationBean dispatcherServlet() {
     ServletRegistrationBean reg = new ServletRegistrationBean(new DispatcherServlet(), "/")
        reg.name = "dispatcherServlet"
        reg.addInitParameter("contextConfigLocation", "")
        reg.addUrlMappings("/api/*")
        reg.loadOnStartup = 2
        reg
    }
}

I am trying to have a separate base URI "/api" specifically for web service calls, that I can leverage for security, etc. However using the above approach will mean that any of my URIs, web service or not, can be reached with "/" or "/api", and provides no concrete segregation.

Is anyone aware of a better approach to set a base path for all @RestController(s) using configuration, without having to formally prefix every controller with /api/? If I am forced to manually prefix the URI for each controller, it would be possible to mistakenly omit that and bypass my security measures specific to web services.

Here is a reference in Stack Overflow to the same type of question, which was never completely answered:

[Spring Boot: Configure a url prefix for RestControllers](https://stackoverflow.com/questions/29439365/spring-boot- configure-a-url-prefix-for-restcontrollers)


Answer

Someone has filed an issue in the Spring MVC Jira and come up with a nice solution, which I am now using. The idea is to use the Spring Expression Language in the prefix placed in each RestController file and to refer to a single property in the Spring Boot application.properties file.

Here is the link of the issue: https://jira.spring.io/browse/SPR-13882