【问题标题】:Swagger 3 with Springboot: Unable to infer base url带有 Springboot 的 Swagger 3:无法推断基本 url
【发布时间】:2021-04-06 05:00:46
【问题描述】:

我使用 Springboot 和 swagger 3:

<!--          SWAGGER                               -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

我对所有端点使用默认的 /api 前缀。

这就是我配置 SwaggerConfig 的方式:

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    public static final String AUTHORIZATION_HEADER = "Authorization";
    @Bean
    public Docket api() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .securityContexts(Collections.singletonList(securityContext()))
                .securitySchemes(Collections.singletonList(apiKey()))
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build().pathMapping("/api");

        return docket;
    }

    private ApiKey apiKey() {
        return new ApiKey("JWT", AUTHORIZATION_HEADER, "header");
    }
  // ......

}

当我尝试访问我的 swagger-ui http://myhost/swagger-ui 时,我会弹出一条消息 Unable to infer base url. This is common when using dynamic servlet registration or when the API is behind an API Gateway. The base url is the root of where all the swagger resources are served. For e.g. if the api is available at http://example.org/api/v2/api-docs then the base url is http://example.org/api/. Please enter the location manually: ,要求我定义位置。

当我手动输入前缀:http://myhost/api 时,一切都很好。

知道如何定义我的 REST API 前缀吗?

【问题讨论】:

标签: spring-boot spring-mvc swagger swagger-ui springfox


【解决方案1】:

我也遇到了你的问题,我也用 swagger 3。最后,我发现是@RestControllerAdvice引起了问题,我使用@RestControllerAdvice来控制统一的响应体。

@RestControllerAdvice
public class ResponseAdvisor implements ResponseBodyAdvice {
    
      @Override
      public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
      }
    
      @Override
      public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
       // do something to package response body o
    }

所以我将其修改为@RestControllerAdvice(basepackage="package of project") 以限制范围。它终于奏效了。所以检查你有没有使用@RestControllerAdvice,如果使用,添加一个basepackage来限制范围,否则会影响swagger 3。希望这可以帮助你。最后,对不起我的英语不好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    • 2018-08-15
    • 2020-01-25
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    • 2019-11-15
    相关资源
    最近更新 更多