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:

  1. WebMvcConfigurer Defines callback methods to customize the Java-based configuration for Spring MVC enabled via @EnableWebMvc.
  2. @EnableWebMvc-annotated configuration classes may implement this interface to be called back and given a chance to customize the default configuration.

ConfigurePathMatch:

  1. 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:

  1. requestMappingHandlerMapping: Return a RequestMappingHandlerMapping ordered at 0 for mapping requests to annotated controllers.
  2. viewControllerHandlerMapping: Return a handler mapping ordered at 1 to map URL paths directly to view names. To configure view controllers, override addViewControllers method.
  3. resourceHandlerMapping: Return a handler mapping ordered at Integer.MAX_VALUE-1 with mapped resource handlers. To configure resource handling, override addResourceHandlers method.