How to set base url for rest in springboot
Introduction:
Instead of maintaining base url for all rest apis in each controller using @RequestMapping(/api/v1). we can set base url at global level of the springboot project using WebMvcConfigurer interface we can override configurePathMatch method with the parameter of PathMatchConfigurer.
Sample code:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class RestBaseUriConfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.addPathPrefix("/api/v1", (clazz)->true);
}
}
WebMvcConfigurer:
- WebMvcConfigurer Defines callback methods to customize the Java-based configuration for Spring MVC enabled via @EnableWebMvc.
- @EnableWebMvc-annotated configuration classes may implement this interface to be called back and given a chance to customize the default configuration.
ConfigurePathMatch:
- Help with configuring HandlerMapping path matching options such as whether to use parsed PathPatterns or String pattern matching with PathMatcher, whether to match trailing slashes, and more.
PathMatchConfigurer:
Configure path matching options. The options are applied to the following:
- requestMappingHandlerMapping: Return a RequestMappingHandlerMapping ordered at 0 for mapping requests to annotated controllers.
- viewControllerHandlerMapping: Return a handler mapping ordered at 1 to map URL paths directly to view names. To configure view controllers, override addViewControllers method.
- resourceHandlerMapping: Return a handler mapping ordered at Integer.MAX_VALUE-1 with mapped resource handlers. To configure resource handling, override addResourceHandlers method.