springboot整合swagger2

什么是Swagger2

编写和维护接口文档是每个程序员的职责,根据 Swagger2 可以快速帮助我们编写最新的API接口文档,再也不用担心开会前仍忙于整理各种资料了,间接提升了团队开发的沟通效率。常用注解swagger通过注解表明该接口会生成文档,包括接口名、请求方法、参数、返回信息的等等。

配置
  • 首先需要在pom.xml添加Swagger2所需要的依赖。
 <!--swagger2-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.1</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.1</version>
        </dependency>
  • 添加Swagger2的配置文件 config -->SwaggerConfig.java
    1.添加@EnableSwagger2


    @EnableSwagger2.png

    2.配置创建文档API信息


    文档api信息.png
  • 注意:此处的params为header中的token令牌,并非所有的请求都需要token参数。
    3.配置Info信息

    info.png

    效果:


    配置信息后的效果.png

    4.关于http请求状态码信息的配置


    请求状态码信息.png

    效果:
    状态码.png
package com.wsy.mybatis_plus_demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.documentation.builders.*;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

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

@Configuration
@EnableSwagger2
public class Swagger2Config {
    @Bean
    public Docket createRestApi(){
        //================== 需要的参数START========================
        List<Parameter> pars = new ArrayList<>();
        ParameterBuilder token = new ParameterBuilder();
        token.name("token").description("token").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
        pars.add(token.build());
        //  ==================== 需要的参数 END ====================
        return new Docket(DocumentationType.SWAGGER_2)
                .globalOperationParameters(pars)//全局非必填参数
                .globalResponseMessage(RequestMethod.GET,customerResponseMessage())
                .globalResponseMessage(RequestMethod.GET,customerResponseMessage())
                .apiInfo(apiInfo())
                .select()
                //项目包所在的controller
                .apis(RequestHandlerSelectors.basePackage("com.wsy.mybatis_plus_demo.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("零食商贩--基础数据API说明文档")
                .description("2019-07-20 开始项目")
                .contact(new Contact("shine_rainbow","http://github.com/shinefairy","804886201@qq.com"))
                //.termsOfServiceUrl("localhost:8080/")
                .version("1.0")
                .build();
    }
    private List<ResponseMessage> customerResponseMessage(){
        List<ResponseMessage> list = new ArrayList<>();
        list.add(new ResponseMessageBuilder().code(200).message("请求成功").build());
        list.add(new ResponseMessageBuilder().code(201).message("资源创建成功").build());
        list.add(new ResponseMessageBuilder().code(204).message("服务器成功处理了请求,但不需要返回任何实体内容").build());
        list.add(new ResponseMessageBuilder().code(400).message("请求失败,具体查看返回业务状态码与对应消息").build());
        list.add(new ResponseMessageBuilder().code(401).message("请求失败,未经过身份认证").build());
        list.add(new ResponseMessageBuilder().code(405).message("请求方法不支持").build());
        list.add(new ResponseMessageBuilder().code(415).message("请求媒体类型不支持").build());
        list.add(new ResponseMessageBuilder().code(500).message("服务器遇到了一个未曾预料的状况,导致了它无法完成对请求的处理").build());
        list.add(new ResponseMessageBuilder().code(503).message("服务器当前无法处理请求,这个状况是临时的,并且将在一段时间以后恢复").build());
        return list;
    }
}

  • Controller中添加相关注解
    1.添加@Api注解在Controller


    @Api.png
    • @Api:用在请求的类上,说明该类的作用

@Api:用在请求的类上,说明该类的作用
tags="说明该类的作用"
value="该参数没什么意义,所以不需要配置"

参数说明

注解 参数 参数说明
@api tags 说明该类的作用,可以在UI界面上看到的注解
@api value 该参数没什么意义,在UI界面上也看到,所以不需要配置

实例:@Api(tags="APP用户注册Controller")

2.添加@ApiOperation等注解在请求方法上


添加注解在请求方法上.png
  • @ApiOperation:用在请求的方法上,说明方法的作用

@ApiOperation:"用在请求的方法上,说明方法的作用"
value="说明方法的作用"
notes="方法的备注说明"

参数说明

注解 参数 参数说明
@api value 说明方法的作用
@api notes 方法的备注说明

实例:@ApiOperation(value="用户注册",notes="手机号、密码都是必输项,年龄随边填,但必须是数字")

  • @ApiImplicitParams:用在请求的方法上,包含一组参数说明

@ApiImplicitParams:用在请求的方法上,包含一组参数说明
@ApiImplicitParam:用在 @ApiImplicitParams 注解中,指定一个请求参数的配置信息
name:参数名
value:参数的汉字说明、解释
required:参数是否必须传
paramType:参数放在哪个地方
· header --> 请求参数的获取:@RequestHeader
· query --> 请求参数的获取:@RequestParam
· path(用于restful接口)--> 请求参数的获取:@PathVariable
· body(不常用)
· form(不常用)
dataType:参数类型,默认String,其它值dataType="Integer"
defaultValue:参数的默认值

示例:

@ApiImplicitParams({
    @ApiImplicitParam(name="mobile",value="手机号",required=true,paramType="form"),
    @ApiImplicitParam(name="password",value="密码",required=true,paramType="form"),
    @ApiImplicitParam(name="age",value="年龄",required=true,paramType="form",dataType="Integer")
})
  • @ApiResponses:用于请求的方法上,表示一组响应

@ApiResponses:用于请求的方法上,表示一组响应
@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
code:数字,例如400
message:信息,例如"请求参数没填好"
response:抛出异常的类

@ApiOperation(value = "select1请求",notes = "多个参数,多种的查询参数类型")
@ApiResponses({
    @ApiResponse(code=400,message="请求参数没填好"),
    @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
})
  • @ApiModel:用于响应类上,表示一个返回响应数据的信息

@ApiModel:用于响应类上,表示一个返回响应数据的信息
(这种一般用在post创建的时候,使用@RequestBody这样的场景,
请求参数无法使用@ApiImplicitParam注解进行描述的时候)
@ApiModelProperty:用在属性上,描述响应类的属性

示例:

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

import java.io.Serializable;

@ApiModel(description= "返回响应数据")
public class RestMessage implements Serializable{

    @ApiModelProperty(value = "是否成功")
    private boolean success=true;
    @ApiModelProperty(value = "返回对象")
    private Object data;
    @ApiModelProperty(value = "错误编号")
    private Integer errCode;
    @ApiModelProperty(value = "错误信息")
    private String message;

    /* getter/setter */
}
package com.wsy.mybatis_plus_demo.controller;


import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.wsy.mybatis_plus_demo.entity.User;
import com.wsy.mybatis_plus_demo.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author shine
 * @since 2019-07-19
 */
@Api(tags = "用户接口")
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    /**
     * 根据id查找用户
     */
    @ApiOperation(value = "获取用户详细信息",notes = "根据url传来的id获取用户对象")
    @ApiImplicitParam(name = "id",value = "用户id",required = true,dataType = "Integer",paramType = "path")
    @GetMapping(value = "/{id}")
    public User getUserById(@PathVariable(value = "id") Integer id){
        User user = userService.getById(id);
        return ObjectUtils.isNotEmpty(user)?user:null;
    }
}


效果:


image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容