如何更改Springfox Swagger 2.0的basePath

时间:2016-03-24 11:13:08

标签: swagger-ui swagger-2.0 springfox

我正在运行服务,可在以下位置访问Swagger UI:

http://serviceURL/swagger-ui.html

然而,它落后于代理,例如:

http://proxyURL/serviceName

Swagger UI生成的URL如下所示:

http://proxyURL/

而不是以serviceName作为后缀的实际URL。 据我所知,这意味着操纵basePath属性。根据文件:

  

swagger API文档无法再描述操作   不同的基本路径。在1.2及更早版本中,每种资源都可以拥有   一个单独的basePath。在2.0中,basePath等价物   (scheme + host + basePath)是为整个规范定义的。

@Api(basePath)已弃用,并且它没有说明要使用的内容以及如何使用它。如何使Swagger生成的路径正确显示?

我使用Spring Boot,Springfox Swagger和注释。

3 个答案:

答案 0 :(得分:6)

@Bean
public Docket newsApi(ServletContext servletContext) {
    return new Docket(DocumentationType.SWAGGER_2).pathProvider(new RelativePathProvider(servletContext) {
        @Override
        public String getApplicationBasePath() {
            return "/serviceName" + super.getApplicationBasePath();
        }
    }).host("proxyURL");
}

答案 1 :(得分:1)

您可以像这样编辑 SwaggerConfiguration

请小心更换package(必须是host 包含您的REST控制器),PATH和所需的@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/"); } }

application.properties

另一种解决方案是通过更改spring-boot URL 上下文路径

编辑倒server.servlet.context-path=/serviceName 文件:

application.yml

或者如果您有一个server: servlet: context-path: /serviceName 文件:

df = df.replace(to_replace='gold (?)', value='gold', regex= True)

"error: unknown extension ?) at position 1"

警告:它将更改您所有Web服务的基本路径,而不仅仅是Swagger

答案 2 :(得分:0)

使用Spring Fox 2.9.2时,无法使用其他用户提到的解决方案。

什么不起作用:

  • 在Docket pathProvider上覆盖getApplicationBasePath
  • 添加server.servlet.context-path = / serviceName

我不知道为什么它们不起作用,但是在我的项目中,使用Springboot 2.1.6.RELEASE和Spring 5.1.8.RELEASE,上面的两个解决方案被忽略了。

因此,我正在尝试另一种方法:https://github.com/springfox/springfox/issues/2817#issuecomment-517753110

根据github问题评论,我需要重写Springfox json序列化类,感谢上帝。 这是代码示例:

with open(PATH+'glove.840B.300d.txt') as f:
    print('File exists')