How to change basePath for Springfox Swagger 2.0

前端 未结 3 1601
Happy的楠姐
Happy的楠姐 2021-02-05 03:16

I\'m running a service, where Swagger UI is accessible at:

http://serviceURL/swagger-ui.html

However, it is behind a proxy, such as:

         


        
3条回答
  •  死守一世寂寞
    2021-02-05 03:49

    You can edit your SwaggerConfiguration like that:

    Take care to replace the package (which need to be the one containing your REST controllers), the host, and the PATH you need

    @Configuration
    @EnableSwagger2
    public class SwaggerConfiguration implements WebMvcConfigurer {
    
        public static final String PATH = "/serviceName";
    
        @Bean
        public Docket api() {
            final var package = "com.martin.rest";
            final var host = "localhost:8080";
    
            return new Docket(DocumentationType.SWAGGER_2)
                    .host(host)
                    .select()
                    .apis(RequestHandlerSelectors.basePackage(package))
                    .paths(PathSelectors.any())
                    .build();
        }
    
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            final var apiDocs = "/v2/api-docs";
            final var configUi = "/swagger-resources/configuration/ui";
            final var configSecurity = "/swagger-resources/configuration/security";
            final var resources = "/swagger-resources";
    
            registry.addRedirectViewController(PATH + apiDocs, apiDocs).setKeepQueryParams(true);
            registry.addRedirectViewController(PATH + resources, resources);
            registry.addRedirectViewController(PATH + configUi, configUi);
            registry.addRedirectViewController(PATH + configSecurity, configSecurity);
            registry.addRedirectViewController(PATH, "/");
        }
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler(PATH + "/**").addResourceLocations("classpath:/META-INF/resources/");
        }
    }
    

    Another solution is by changing the spring-boot URL context-path:

    Edit pour application.properties file:

    server.servlet.context-path=/serviceName
    

    Or if you have an application.yml file:

    server:
      servlet:
        context-path: /serviceName
    

    Warning: It will change the base path of all your web services, not only Swagger

提交回复
热议问题