抱歉,您的浏览器无法访问本站

本页面需要浏览器支持(启用)JavaScript


了解详情 >

一、整合

1. 引入依赖

pom.xml

        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

2. 配置类

@EnableSwagger2
@Configuration
public class Swagger2Config {

  @Bean
  public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
        .pathMapping("/")
        .select()
        .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
        .paths(PathSelectors.any())
        .build()
        .apiInfo(
            new ApiInfoBuilder()
                .title("SpringBoot整合Swagger")
                .description("描述内容......")
                .version("9.0")
                // 联系人
                .contact(new Contact("Seepine", "https://seepine.com", "seepine@outlook.com"))
                .license("The Apache License")
                .licenseUrl("https://seepine.com")
                .build());
  }
}

3.访问

访问地址http://localhost:8080/swagger-ui.html即可

二、常见错误

1.Unable to infer base url.

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:

  • 是否加了@EnableSwagger2注解
  • 配置类是否被 SpringBoot 扫描
  • 权限拦截排除,例如.excludePath("/swagger-resources/**", "/v2/api-docs", "/webjars/**", "swagger-ui.html")
  • 是否做了全局统一返回封装,需要@RestControllerAdvice(basePackages = "com.example.controller")指定拦截包路径,避免拦截到 Swagger

评论