SpringBoot集成swagger、yapi

一、如何使用

第一步,引入pom文件

        
        
            io.springfox
            springfox-swagger2
            2.9.2
        
        
            io.springfox
            springfox-swagger-ui
            2.9.2
        
        
        
            com.github.xiaoymin
            swagger-bootstrap-ui
            1.9.5
        

第二步,编写swagger配置类

package com.tracy.swagger.config;

import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import javax.xml.ws.Response;
import java.util.ArrayList;
import java.util.List;

/**
 * @EnableSwaggerBootstrapUI   swagger页面优化 使用时账密验证
 * @EnableSwagger2  开启swagger
 * swagger.enable 项目动态启用swagger
 */
@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI
@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
public class SwaggerConfig {

    @Bean
    public Docket docket() {
        //可以通过此方式添加全局header
        ParameterBuilder parameterBuilder = new ParameterBuilder();
        List heads = new ArrayList();
        parameterBuilder.name("token")
                .description("访问令牌")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .required(false)
                .build();
        heads.add(parameterBuilder.build());

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .genericModelSubstitutes(Response.class)
                .forCodeGeneration(true)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.tracy.swagger.controller"))
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(heads);
    }
    
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("API文档")
                .description("采用swagger2")
                .termsOfServiceUrl("")
                .version("1.0")
                .build();
    }
}

第三步,application.yml配置

server:
  port: 11111
swagger:
  enable: true  #项目是否开发swagger
  basic:
    enable: true #是否开启权限验证
    username: tracy #账号
    password: 123456 #密码

第四步,编写controller、entity、vo、bo

package com.tracy.swagger.controller;

import com.tracy.swagger.bo.UserBo;
import com.tracy.swagger.entity.User;
import com.tracy.swagger.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/swagger")
@Api(tags ="swagger测试类")
public class SwaggerController {


    @GetMapping(value = "/getUser")
    @ApiOperation(value = "获取用户信息",notes = "根据用户id获取用户信息")
    @ApiImplicitParam(name = "id",value = "用户id",required = true,paramType = "query",dataType = "string")
    public Result getUser(@RequestParam("id")Long id){
        User user = new User(1L,"swagger",18,false,new Date());
        Result result = new Result<>(Result.SUCCESS_STATUS,"SUCCESS",user);
        return result;
    }

    @PostMapping(value = "/addUser")
    @ApiOperation(value = "新增用户",notes = "新增用户")
    public Result addUser(@RequestBody UserBo userBo){
        User user = new User(1L,"swagger",18,false,new Date());
        Result result = new Result<>(Result.SUCCESS_STATUS,"SUCCESS",user);
        return result;
    }

    @PostMapping(value = "/updateUser")
    @ApiOperation(value = "更新用户",notes = "更新用户")
    public Result updateUser(@RequestBody UserBo userBo){
        User user = new User(1L,"swagger",18,false,new Date());
        Result result = new Result<>(Result.SUCCESS_STATUS,"SUCCESS",user);
        return result;
    }

    @DeleteMapping(value = "/deleteUser")
    @ApiOperation(value = "删除用户",notes = "根据用户id删除用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "用户id",required = true,paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "authority",value = "用户权限",required = true,paramType = "header",dataType = "string")
    })
    public Result deleteUser(@RequestParam("id")Long id){
        Result result = new Result<>(Result.SUCCESS_STATUS,"SUCCESS",true);
        return result;
    }

}
package com.tracy.swagger.entity;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.Date;

@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "用户",description = "用户对象模型")
public class User implements Serializable {

    private static final long serialVersionUID = 7497034210240490279L;

    @ApiModelProperty(name="id",value = "用户Id",dataType = "Long")
    private Long id;

    @ApiModelProperty(name="name",value = "用户名",dataType = "String")
    private String name;

    @ApiModelProperty(name="age",value = "年龄",dataType = "Integer")
    private Integer age;

    @ApiModelProperty(name="deleted",value = "是否删除",dataType = "Boolean")
    private Boolean deleted;

    @ApiModelProperty(name="birthday",value = "生日",dataType = "Date")
    private Date birthday;
}

 

package com.tracy.swagger.vo;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "result",description = "返回值对象")
public class Result implements Serializable {

    private static final long serialVersionUID = -3093856310515437414L;

    public static final int SUCCESS_STATUS = 200;

    public static final int FAILURE_STATUS = -1;

    @ApiModelProperty(name="code",value = "状态 200:成功 其余异常",dataType = "int")
    private int code = SUCCESS_STATUS;

    @ApiModelProperty(name="message",value = "错误信息",dataType = "String")
    private String message;

    @ApiModelProperty(name="data",value = "返回数据主体",dataType = "T")
    private T data;

}

 

package com.tracy.swagger.bo;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.Date;

@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "用户对象",description = "用户")
public class UserBo implements Serializable {

    @ApiModelProperty(name="id",value = "用户id,更新用户信息时必传",dataType = "Long")
    private Long id;

    @ApiModelProperty(name="name",value = "用户名",dataType = "String")
    private String name;

    @ApiModelProperty(name="age",value = "年龄",dataType = "Integer")
    private Integer age;

    @ApiModelProperty(name="deleted",value = "是否删除",dataType = "Boolean")
    private Boolean deleted;

    @ApiModelProperty(name="birthday",value = "生日",dataType = "Date")
    private Date birthday;
}

第五步,启动,展示效果

权限验证:

SpringBoot集成swagger、yapi_第1张图片

普通效果:http://127.0.0.1:11111/swagger-ui.html

SpringBoot集成swagger、yapi_第2张图片

增强UI效果:http://127.0.0.1:11111/doc.html

SpringBoot集成swagger、yapi_第3张图片

第六步,集成yapi

yapi测试环境地址:http://yapi.demo.qunar.com/

1.采用上传swagger的方式,转为yapi,swagger文件地址 http://127.0.0.1:11111/v2/api-docs

2.swagger数据导入

SpringBoot集成swagger、yapi_第4张图片

SpringBoot集成swagger、yapi_第5张图片

 

二、swagger主要注解使用

1.@Api作用在Controller类,类的描述

value	    	url的路径值
tags	    	如果设置这个值、value的值会被覆盖
produces		For example, "application/json, application/xml"
consumes		For example, "application/json, application/xml"
protocols		Possible values: http, https, ws, wss.
authorizations	高级特性认证时配置
hidden			配置为true 将在文档中隐藏

2.@ApiOperation作用在Controller的方法,方法的描述

value				url的路径值
tags				如果设置这个值、value的值会被覆盖
description			对api资源的描述
basePath			基本路径可以不配置
produces			For example, "application/json, application/xml"
consumes			For example, "application/json, application/xml"
protocols			Possible values: http, https, ws, wss.
authorizations		高级特性认证时配置
hidden				配置为true 将在文档中隐藏
response			返回的对象
responseContainer	这些对象是有效的 "List", "Set" or "Map".,其他无效
httpMethod			"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS" and "PATCH"
code				http的状态码 默认 200
extensions			扩展属性

3.@ApiImplicitParams、@ApiImplicitParam作用在Controller的方法上,参数的描述

name            参数名
value           参数名描述
paramType		参数类型 path-> /user/{id}  query->/user?id=1 body->RequestBody header->请求头  form->表单提交
dataType        参数数据类型 string int long
required        是否必要 默认false
defaultValue    参数的默认值

三、参考文档

swagger-bootstrap-ui文档地址:https://doc.xiaominfo.com/

代码地址:https://gitee.com/jiaobai/swagger

你可能感兴趣的:(java)