Skip to content
标签
api文档
字数
1608 字
阅读时间
8 分钟

一、概述

1.1 注解

java
//用在请求的接口类上,对接口类进行说明 
@Api(tags="")
//  用在请求的方法上,说明方法的用途、作用
//  httpMethod属性:指定当前方法访问时使用的请求方式。
//注意:如果是RequestMapping且 没有设置这个属性,swagger为当前方法的每一个HTTP请求方式都生成对应的文档条目。
@ApiOperation(value="")
// 用在请求的方法上,@ApiImplicitParam参数结合
@ApiImplicitParams
// 用在请求的方法上,说明请求参数的信息
@ApiImplicitParam
// 用在请求的方法上,@ApiResponse参数集合
@ApiResponses
// 用在请求的方法上,说明响应参数编码及描述信息 code:数字,例如400 message:信息,例如"请求参数没填好" response:抛出异常的类
@ApiResponse
// 用在实体类上,对方法引用(入参或出参)的model进行说明
@ApiModel
// 用在实体类的属性上,对各属性信息进行说明
@ApiModelProperty

二、使用示例

2.1 与Springboot集成

依赖

groovy
implementation 'io.springfox:springfox-swagger2:2.9.2'
implementation 'io.springfox:springfox-swagger-ui:2.9.2'

配置类

java
package com.note.technology.swagger.config;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.Swagger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.documentation.builders.*;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import springfox.documentation.swagger2.mappers.ServiceModelToSwagger2Mapper;
import springfox.documentation.swagger2.mappers.ServiceModelToSwagger2MapperImpl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Classname SwaggerConfig
 * @Description swagger配置类
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Value("${swagger2.enable:true}")
    private boolean enable;

    @Bean("用户模块")
    public Docket userApis() {
        final List<ResponseMessage> globalResponses = Arrays.asList(
                new ResponseMessageBuilder()
                        .code(200)
                        .message("OK[完成]")
                        .build()
                );
        List<Parameter> pars = new ArrayList<>();
        ParameterBuilder tokenPar = new ParameterBuilder();
        tokenPar
                // 名字
                .name("全局参数1")
                // 描述
                .description("全局参数1描述")
                // 参数类型
                .modelRef(new ModelRef("string"))
                // 参数传入类型 header query  cookie
                .parameterType("header")
                //是否必传
                .required(false).build();
        pars.add(tokenPar.build());
        return new Docket(DocumentationType.SWAGGER_2)
                // 是否启用Swagger
                .enable(enable)
                // 定义全局响应信息 ,多个请求方式需要配置多个。
                .globalResponseMessage(RequestMethod.GET, globalResponses)
                // 定义全局请求参数
                .globalOperationParameters(pars)
                // 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息)
                .apiInfo(apiInfo())
                // 设置哪些接口暴露给Swagger展示
                .select()
                // 扫描所有有注解的api,用这种方式更灵活
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                // 扫描指定包中的swagger注解
                // .apis(RequestHandlerSelectors.basePackage("com.ruoyi.project.tool.swagger"))
                // 扫描所有 .apis(RequestHandlerSelectors.any())
                // 可通过
                // url路径信息,可自定定义过滤
                // PathSelectors.ant("/**/*.url*") 选择包含某些信息的url
                // 路径排除
                //Predicate<String> pathPredicate = (selector)->!selector.contains(".url"); 将对象传入paths中
                .paths(PathSelectors.any())
                .build()
                /* 设置安全模式,swagger可以设置访问token */
                .securitySchemes(securitySchemes())
//                .securityContexts(securityContexts())
                //设置请求的统一前缀 会拼接在请求的方法前
//                .pathMapping("123")
                ;
    }

    /**
     * 安全模式,这里指定token通过Authorization头请求头传递
     */
    private List<ApiKey> securitySchemes() {
        List<ApiKey> apiKeyList = new ArrayList<ApiKey>();
        apiKeyList.add(new ApiKey("Authorization", "Authorization", "header"));
        return apiKeyList;
    }

    /**
     * 安全上下文
     */
    private List<SecurityContext> securityContexts() {
        List<SecurityContext> securityContexts = new ArrayList<>();
        securityContexts.add(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        .forPaths(PathSelectors.regex("^(?!auth).*$"))
                        .build());
        return securityContexts;
    }

    /**
     * 默认的安全上引用
     */
    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        List<SecurityReference> securityReferences = new ArrayList<>();
        securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
        return securityReferences;
    }

    /**
     * 添加摘要信息
     */
    private ApiInfo apiInfo() {
        // 用ApiInfoBuilder进行定制
        return new ApiInfoBuilder()
                // 设置标题
                .title("标题:接口文档")
                // 描述
                .description("描述:这是描述信息")
                // 作者信息
                .contact(new Contact("123", null, null))
                // 版本
                .version("版本号:" + "1.0.0")
                .build();
    }


    /**
     * 重构apidocs Documentation 转换 Swagger 方法
     *
     * @return
     */
//    @Bean
//    @Primary
//    public ServiceModelToSwagger2Mapper serviceModelToSwagger2Mapper() {
//        return new ServiceModelToSwagger2MapperImpl() {
//            @Override
//            public Swagger mapDocumentation(Documentation from) {
//                Swagger swagger = super.mapDocumentation(from);
////                SwaggerExtend swaggerExtend = new SwaggerExtend(apidocProxyPath);
////                BeanUtils.copyProperties(swagger, swaggerExtend);
////                return swaggerExtend;
//                return swagger;
//            }
//        };
//    }
}

测试使用

Controller

java
package com.note.technology.swagger.controller;

import com.note.technology.swagger.model.RequestDemo;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;

/**
 * @Classname DemoController
 * @Description swagger测试类
 */
@RestController
// 用于接口类上,tag用于对接口类的说明
@Api(tags="swagger测试接口")
public class DemoController {

    //ApiOperation没有设置httpMethod属性且使用requestMapping,会在swagger上创建多个方法。getMapping只会创建单个
    @RequestMapping(value ="demo")
    // 用在请求的方法上,说明方法的用途、作用
    // httpMethod属性:指定当前方法访问时使用的请求方式。
    // 注意:如果没有设置这个属性,swagger为当前方法的每一个HTTP请求方式都生成对应的文档条目。
    @ApiOperation(value = "测试方法",httpMethod = "GET")
    // 用在请求的方法上,标名参数集合
    @ApiImplicitParams(
            {
                    /**
                     *value:参数含义说明
                     *required:是否必须
                     *paramType
                     *   path 以地址的形式提交数据
                     *	query 直接跟参数完成自动映射赋值
                     *	body 以流的形式提交 仅支持POST
                     *	header 参数在request headers 里边提交
                     *	form 以form表单的形式提交 仅支持POST
                     *	body(不常用)
                     *	form(不常用)
                     *dataType:参数类型,默认String,其它值dataType="Integer"
                     *defaultValue:参数的默认值
                     */
                    @ApiImplicitParam(name="name",value="参数1",required=true),
                    @ApiImplicitParam(name="age",value="参数2",required=true)
            }
    )
    //@ApiResponses 用在请求的方法上,表示一组响应code值说明
    // @ApiResponse 用在@ApiResponses中,一般用于表达一个错误的响应信息
    //code:数字,例如400
    //message:信息,例如"请求参数没填好"
    //response:抛出异常的类
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 404,message = "找不到资源"),
    })
    public String demoTest(String name,Integer age){
        return name+age;
    }

    @PostMapping("demo2")
    @ApiOperation(value = "测试方法2")
    public RequestDemo demoTest2(@RequestBody RequestDemo requestDemo){
        return requestDemo;
    }
}

Model

java
package com.note.technology.swagger.model;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

/**
 * @Classname RequestDemo
 * @Description 请求的测试model
 */
// 对model进行说明
@ApiModel("测试model")
public class RequestDemo {

    // 对model中个参数进行说明
    @ApiModelProperty("model参数1")
    private String aa;

    @ApiModelProperty("model参数2")
    private String bb;

    public String getAa() {
        return aa;
    }

    public void setAa(String aa) {
        this.aa = aa;
    }

    public String getBb() {
        return bb;
    }

    public void setBb(String bb) {
        this.bb = bb;
    }

    @Override
    public String toString() {
        return "RequestDemo{" +
                "aa='" + aa + '\'' +
                ", bb='" + bb + '\'' +
                '}';
    }
}

Zuul网关配置

java
package com.note.technology.swagger.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.LinkedList;
import java.util.List;

/**
 * @Classname GatewaySwaggerConfig
 * @Description Zuul网关swagger配置
 */
@EnableSwagger2
@Configuration
@Primary //多个bean时 此类优先使用
public class GatewaySwaggerConfig extends SwaggerConfig implements SwaggerResourcesProvider {

    @Autowired
    RouteLocator routeLocator;

    @Override
    public List<SwaggerResource> get() {
        //利用routeLocator动态引入微服务
        List<SwaggerResource> resources = new LinkedList<>();
        resources.add(swaggerResource("zuul","/v2/api-docs","1.0"));
        //循环 使用Lambda表达式简化代码
        routeLocator.getRoutes().forEach(route ->{
            //动态获取
            resources.addAll(swaggerResources(route.getId(),route.getFullPath().replace("**", "v2/api-docs"), "1.0"));
        });
        return resources;
    }

    private List<SwaggerResource> swaggerResources(String name,String location, String version) {
        List<SwaggerResource> resources = new LinkedList<>();
        resources.add(swaggerResource(name,location,version));
        return resources;
    }


    private SwaggerResource swaggerResource(String name,String location, String version) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion(version);
        return swaggerResource;
    }
}