How to set base url for rest in spring boot?

后端 未结 18 2313
日久生厌
日久生厌 2020-11-28 03:23

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\'

相关标签:
18条回答
  • 2020-11-28 03:32

    This solution applies if:

    1. You want to prefix RestController but not Controller.
    2. You are not using Spring Data Rest.

      @Configuration
      public class WebConfig extends WebMvcConfigurationSupport {
      
      @Override
      protected RequestMappingHandlerMapping createRequestMappingHandlerMapping() {
          return new ApiAwareRequestMappingHandlerMapping();
      }
      
      private static class ApiAwareRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
      
          private static final String API_PATH_PREFIX = "api";
      
          @Override
          protected void registerHandlerMethod(Object handler, Method method, RequestMappingInfo mapping) {
              Class<?> beanType = method.getDeclaringClass();
              if (AnnotationUtils.findAnnotation(beanType, RestController.class) != null) {
                  PatternsRequestCondition apiPattern = new PatternsRequestCondition(API_PATH_PREFIX)
                          .combine(mapping.getPatternsCondition());
      
                  mapping = new RequestMappingInfo(mapping.getName(), apiPattern, mapping.getMethodsCondition(),
                          mapping.getParamsCondition(), mapping.getHeadersCondition(), mapping.getConsumesCondition(),
                          mapping.getProducesCondition(), mapping.getCustomCondition());
              }
              super.registerHandlerMethod(handler, method, mapping);
          }
      }
      

      }

    This is similar to the solution posted by mh-dev, but I think this is a little cleaner and this should be supported on any version of Spring Boot 1.4.0+, including 2.0.0+.

    0 讨论(0)
  • 2020-11-28 03:32

    worked server.contextPath=/path

    0 讨论(0)
  • 2020-11-28 03:34

    I might be a bit late, BUT... I believe it is the best solution. Set it up in your application.yml (or analogical config file):

    spring:
        data:
            rest:
                basePath: /api
    

    As I can remember that's it - all of your repositories will be exposed beneath this URI.

    0 讨论(0)
  • 2020-11-28 03:38

    With spring-boot 2.x you can configure in application.properties:

    spring.mvc.servlet.path=/api
    
    0 讨论(0)
  • 2020-11-28 03:39

    With Spring Boot 1.2+ (<2.0) all it takes is a single property in application.properties:

    spring.data.rest.basePath=/api
    

    ref link : https://docs.spring.io/spring-data/rest/docs/current/reference/html/#getting-started.changing-base-uri

    For 2.x, use

    server.servlet.context-path=/api
    
    0 讨论(0)
  • 2020-11-28 03:40

    For Boot 2.0.0+ this works for me: server.servlet.context-path = /api

    0 讨论(0)
提交回复
热议问题