I\'m trying to to mix mvc and rest in a single spring boot project.
I want to set base path for all rest controllers (eg. example.com/api) in a single place (I don\'
Try using a PathMatchConfigurer (Spring Boot 2.x):
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.addPathPrefix("api", HandlerTypePredicate.forAnnotation(RestController.class));
}
}
You can create a custom annotation for your controllers:
Use it instead of the usual @RestController on your controller classes and annotate methods with @RequestMapping.
Works fine in Spring 4.2!
For those who use YAML configuration(application.yaml).
Note: this works only for Spring Boot 2.x.x
server:
servlet:
contextPath: /api
If you are still using Spring Boot 1.x
server:
contextPath: /api
Per Spring Data REST docs, if using application.properties, use this property to set your base path:
spring.data.rest.basePath=/api
But note that Spring uses relaxed binding, so this variation can be used:
spring.data.rest.base-path=/api
... or this one if you prefer:
spring.data.rest.base_path=/api
If using application.yml, you would use colons for key separators:
spring:
data:
rest:
basePath: /api
(For reference, a related ticket was created in March 2018 to clarify the docs.)
I couldn't believe how complicate the answer to this seemingly simple question is. Here are some references:
There are many differnt things to consider:
server.context-path=/api
in application.properties
you can configure a prefix for everything.(Its server.context-path not server.contextPath !)spring.data.rest.base-path
in application.properties
. But plain @RestController
won't take this into account. According to the spring data rest documentation there is an annotation @BasePathAwareController
that you can use for that. But I do have problems in connection with Spring-security when I try to secure such a controller. It is not found anymore.Another workaround is a simple trick. You cannot prefix a static String in an annotation, but you can use expressions like this:
@RestController
public class PingController {
/**
* Simple is alive test
* @return <pre>{"Hello":"World"}</pre>
*/
@RequestMapping("${spring.data.rest.base-path}/_ping")
public String isAlive() {
return "{\"Hello\":\"World\"}";
}
}
You can create a custom annotation for your controllers:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@RestController
@RequestMapping("/test")
public @interface MyRestController {
}
Use it instead of the usual @RestController on your controller classes and annotate methods with @RequestMapping.
Just tested - works in Spring 4.2!