SpringBoot项目整合Knife4j接口文档

发布于:2024-04-20 ⋅ 阅读:(22) ⋅ 点赞:(0)

什么是接口文档?

写满接口信息的文档,每条接口包括:请求参数,响应参数,接口地址,接口名称,请求类型,请求格式,备注

谁用接口文档

后端or负责人来提供,后端和前端都要使用

为什么需要接口文档

1.有个书面内容(归档),便于大家参考和查阅,便于沉淀和维护
2.便于前端和后端开发对接,前后端联调的介质,后端->接口文档-<前端
3.好的接口文档支持在线测试,可以作为工具提高开发效率

怎么做接口文档

1.手写
2.自动化接口文档生成:Swagger,Postman,apifox,apipost,eolink
knife4j官网
https://doc.xiaominfo.com/

springboot如何整合knife4j?

1.引入依赖

<!--引入Knife4j的官方start包,Swagger2基于Springfox2.10.5项目-->
<dependency>
  <groupId>com.github.xiaoymin</groupId>
  <!--使用Swagger2-->
  <artifactId>knife4j-spring-boot-starter</artifactId>
  <version>2.0.9</version>
</dependency>

2.在config目录下创建Knife4j配置依赖

(注意要填写控制器所在包的位置)

package com.example.usercenterbackend.config; /**
 * @author Shier
 * @date 2023/02/02
 * 自定义 Swagger 接口文档的配置
 */

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

/**
 * @author: 诨号无敌鸭
 * @date: 2022/11/20
 * @ClassName: yupao-backend01
 * @Description: 自定义 Swagger 接口文档的配置
 */
@Configuration
@EnableSwagger2WebMvc //启用 Swagger2 在 Spring MVC 环境中的使用。
@Profile({"dev", "test"})   //仅在"dev"和"test"两个环境下生效,即只有在开发和测试环境下才会启用 Swagger 接口文档配置。
public class SwaggerConfig {

    @Bean(value = "defaultApi2")
    public Docket defaultApi2() {
        return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(apiInfo())
        .select()
        // 这里一定要标注你控制器的位置
        .apis(RequestHandlerSelectors.basePackage("com.example.usercenterbackend.controller"))
        .paths(PathSelectors.any())
        .build();
    }

    /**
     * api 信息
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
        .title("无敌鸭用户中心")
        .description("无敌鸭用户中心接口文档")
        .termsOfServiceUrl("https://github.com/Serendipityzhezi")
        .contact(new Contact("诨号无敌鸭", "https://blog.csdn.net/m0_74870396?spm=1000.2115.3001.5343","1342558165@qq.com"))
        .version("1.0")
        .build();
    }
}

3.在appliacation.yml中进行配置

spring:
 mvc:
  pathmatch:
    matching-strategy: ant_path_matcher
    #路径匹配策略 
 profiles:
  active: dev
  #开发环境设置

4.启动Spring Boot工程,在浏览器中访问:http://localhost:后端端口号/doc.html

即可访问到接口文档页面