掘金 后端 ( ) • 2024-04-08 14:24

项目集成Swagger

大家好,我是小玺,今天给大家讲解一款Swagger增强版本工具的集成使用

集成背景

一般我们在对接前后端的时候,都需要提供相应的接口文档。对于后端来说,编写接口文档即费时费力,还会经常因为没有及时更新,导致前端对接时出现实际接口与文档不一致。而且手写接口文档还容易出错,而swagger很好的解决了这个痛点

  • 支持 API 自动生成同步的在线文档:使用 Swagger 后可以直接通过代码生成文档,不再需要自己手动编写接口文档了,对程序员来说非常方便,可以节约写文档的时间去学习新技术。
  • 提供 Web 页面在线测试 API:光有文档还不够,Swagger 生成的文档还支持在线测试。参数和格式都定好了,直接在界面上输入参数对应的值即可在线测试接口。
  • 类似技术:RAML、Blueprint、Apidoc

1、相关模块引入swagger依赖

        <!-- Swagger-ui增强版start -->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>3.0.3</version>
        </dependency>
        <!-- Swagger-ui增强版end -->

2、SpringBoot 配置文件下进行如下自定义配置

knife4j:
  enable: true
  #自定义配置
  customize:
    #分组名
    group:
      name: 1.5.0
    #联系人信息
    contact:
      name: 事业部
      email: [email protected]
      url: https://mail.test.com.cn/
    # 主机名
    host: 127.0.0.1
    # 标题
    title: API在线文档
    # 简介
    description: 订单模块Feign接口文档
    # 版本
    version: 1.5.0
    # 需要扫描controller层包的目录,扫描类必须用最新的@RestController注解,支持多路径扫描,使用;分割
    paths: com.expamle.test.apiService;
  #生产版本禁用swagger
  production: false
  #配置访问账号密码
  basic:
    enable: true
    username: admin
    password: 123456
  documents:
    - group: 1.5.0
      name: 开发文档
      # 某一个文件夹下单个.md文件
      locations: classpath:markdown/*

3、配置类完成Swagger配置(可直接使用)

package com.example.config;
​
import com.github.xiaoymin.knife4j.spring.extension.OpenApiExtensionResolver;
import lombok.Setter;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.RequestHandler;
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;
​
import java.util.List;
import java.util.function.Predicate;
​
/**
 * swagger-ui配置类
 *
 * @author xiaoxi
 * @date 2022/7/5
 **/
@Configuration
@EnableSwagger2WebMvc
@Setter
public class Knife4jConfiguration {
    /**
     * 指定Controller包路径
     */
    @Value("#{'${knife4j.customize.paths}'.split(';')}")
    private String[] paths;
    /**
     * 分组名称
     */
    @Value("${knife4j.customize.group.name:1.5.0}")
    private String groupName;
    /**
     * 主机名
     */
    @Value("${knife4j.customize.host:127.0.0.1}")
    private String host;
    /**
     * 标题
     */
    @Value("${knife4j.customize.title:API在线文档}")
    private String title;
    /**
     * 简介
     */
    @Value("${knife4j.customize.description:WMS产品项目OMS模块接口文档}")
    private String description;
    /**
     * 联系人
     */
    @Value("${knife4j.customize.contact.name:综合物流事业部}")
    private String contactName;
    /**
     * 联系网址
     */
    @Value("${knife4j.customize.contact.url:https://mail.test.com.cn/}")
    private String contactUrl;
    /**
     * 联系邮箱
     */
    @Value("${knife4j.customize.contact.email:[email protected]}")
    private String contactEmail;
    /**
     * 版本号
     */
    @Value("${knife4j.customize.version:1.5.0}")
    private String version;
​
    @Autowired
    private OpenApiExtensionResolver openApiExtensionResolver;
​
    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .host(host)
                .apiInfo(apiInfo())
                .groupName(groupName)
                .select()
                .apis(getBasePackages())
                .paths(PathSelectors.any())
                .build()
                .extensions(openApiExtensionResolver.buildExtensions(groupName));
    }
​
    /**
     * 获取API扫描配置
     * @return Predicate
     */
    private Predicate<RequestHandler> getBasePackages() {
        Predicate<RequestHandler> predicate = RequestHandlerSelectors.withClassAnnotation(RestController.class);
        if(paths!=null&&paths.length>0) {
            for (String basePackage : paths) {
                if (StringUtils.isEmpty(basePackage)){
                    continue;
                }
                predicate = predicate.and(RequestHandlerSelectors.basePackage(basePackage));
            }
        }
        return predicate;
    }
​
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(title)
                .description(description)
                .contact(new Contact(contactName, contactUrl, contactEmail))
                .version(version)
                .build();
    }
}

4、Swagger常用注解说明

4.1、@Api

用于类;表示标识这个类是swagger的资源

@Api(value="订单管理",tags={"订单管理接口"})
4.2、@ApiOperation

用于方法;表示一个http请求的操作(value用于方法描述;notes用于提示内容;tags可以重新分组)

@ApiOperation(value = "核对重量回写到订单",notes = "核对重量回写到订单信息")
4.3、@ApiOperationSupport

用于方法;标识方法提供信息(order:对应增-10 删-20改-30 查-40 ,author标识作者)

@ApiOperationSupport(order = 30,author = "张三")
4.4、@ApiImplicitParams + @ApiImplicitParam

用于方法;描述参数信息(非实体类)

value–字段说明 name–重写属性名字 dataType–重写属性类型 required–是否必填 example–举例说明 hidden–隐藏

注:不建议使用 @ApiParam,在方法参数中使用该注解代码可读性和维护方面较差

tips:针对Map或者JSONObject这种动态参数的,可通过增强注解 @DynamicParameters+ @DynamicParameter代替上述两个注解

@ApiImplicitParams({
        @ApiImplicitParam(name = "orderNo", value = "订单号", required = true, dataType = "string", example = "MA220705000001"),
        @ApiImplicitParam(name = "actualChargeWeight", value = "实际计费重", required = true, dataType = "BigDecimal", example = "10.0"),
        @ApiImplicitParam(name = "actualChargeCubage", value = "实际计费体积", required = true, dataType = "BigDecimal", example = "10.0")
})
4.5、@ApiModel

用于类;表示对类进行说明,用于参数用实体类接收

value–表示对象名 description–描述

......
    @ApiOperation(value = "费用重算")
    @ApiOperationSupport(order = 30)
    @PostMapping("/updateContainer")
    void updateContainer(@RequestBody OmsOrderContainerListVo omsOrderContainerListVo);
......
​
@ApiModel(value = "订单装柜信息VO集合",description = "订单装柜信息VO集合")
public class OmsOrderContainerListVo {
    ......
}
4.6、@ApiModelProperty
    用于方法字段;描述参数信息(实体类)

value–字段说明 name–重写属性名字 dataType–重写属性类型 required–是否必填 example–举例说明 hidden–隐藏

    @ApiModelProperty(name = "orderNo", value = "订单号", required = true, dataType = "string", example = "MA220705000001",hidden = false)
    private String orderNo;
    @ApiModelProperty(name = "omsOrderContainersVoList",value = "装柜信息",required = true)
    List<OmsTrainOrderContainerVO> omsOrderContainersVoList;

注:上述示例中OmsTrainOrderContainerVO类也要求需要 @ApiModel+@ApiModelProperty注解进行参数说明

knife4j开发文档:https://doc.xiaominfo.com/knife4j/documentation/author.html

swagger2开发文档:https://github.com/swagger-api/swagger-core/wiki/Annotations

集成项目swagger接口访问地址:【项目访问地址+/doc.html#/home】如,http://127.0.0.1:8085/doc.html#/home