Spring Boot整合 Swagger + Knife4j 框架,自动生成接口文档


后端整合 Swagger + Knife4j 接口文档

Swagger原理

  1. 引入依赖(Swagger 或 Knife4j):https://swagger.io/ 、https://doc.xiaominfo.com/
  2. 自定义 swagger 配置类。
  3. 定义需要生成接口文档的代码位置(比如:Controller)。
    • 注意:线上环境不要把接口地址路暴露出去!!!——如何隐藏呢?
    • 可以通过在 SwaggerConfig 配置文件的类上加上 @Profile({"dev","test"}),限定配置仅在部分环境开启
  4. 启动即可
  5. 可以通过在Controller层的方法上添加 诸如:@Api 等注解来自定义生成对应接口的描述信息。

Knife4j

对Swagger的一个增强,类似Mybatis和Mybatis-Plus框架之间的关系。


注意:如果 Spring Boot version ≥ 2.6,需要在yml配置文件添加如下配置:
Spring:
  mvc:
    path match:
      # Springboot2.6以后将SpringMVC 默认路径匹配策略从 AntPathMatcher 更改为了PathPatternParser,导致集成swagger时会报错
      matching-strategy: ant_path_matcher
  1. 引入swagger / Knife4j 框架(二选一)

    Swagger 引入参考:

    https://www.jb51.net/program/324112qog.htm

    <!-- 引入 Knife4j -->
    <dependency>
        <groupId>com.github.xiaoymin</groupId>
        <artifactId>knife4j-spring-boot-starter</artifactId>
        <version>3.0.3</version>
    </dependency>
    
  2. 整合 Swagger 框架后,需要创建Swagger配置依赖,添加配置类

    @Configuration
    @EnableSwagger2WebMvc
    @Profile({"dev","test"})
    public class SwaggerConfig {
    
        @Bean(value = "defaultApi2")
        public Docket defaultApi2() {
            Docket docket = new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(new ApiInfoBuilder()
                            .title("测试api文档")
                            .description("用户中心接口endangered")
                            .termsOfServiceUrl("http://www.baidu.com")
    //                        .contact("abc@qq.com")
                            .version("1.0")
                            .build())
                    .groupName("2.X版本")
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.mhd.usercenter.controller"))
                    .paths(PathSelectors.any())
                    .build();
            return docket;
        }
    }
    
SpringBoot
JAVA-技能点
知识点