Spring学习笔记(三十三)——SpringBoot集成Swagger

66 篇文章 11 订阅

Swagger相关介绍

1. Swagger是什么
Swagger 是一个规范且完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务,可以让你更好的书写API文档规范且完整。

2. 为什么要使用Swagger
在实际的开发中,前后端多多少少都被接口文档的编写的调用折磨过。前端经常抱怨后端给的接口文档与实际情况不一致;后端又觉得编写及维护接口文档会耗费不少精力,经常来不及更新。其实无论是前端调用后端,还是后端调用后端,都期望有一个好的接口文档。

3. Swagger 的优势

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

Swagger的配置和使用

1. 添加相关的依赖坐标

		<!--Swagger2-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.6</version>
        </dependency>

2. 在配置文件中配置Swagger

# 配置swagger
swagger.basePackage:cn.kt.springboot_cache
swagger.title:如我西沉のAPI
swagger.description:干嘛这么想不开,要在脸上贴个输字。
swagger.version:V1.0

3. 添加swagger配置类

package cn.kt.springboot_cache.config;

/**
 * Created by tao.
 * Date: 2021/10/12 9:21
 * 描述:
 */

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.EnableSwagger2;

/**
 * Swagger配置类.
 */

// Swagger的开关,表示已经启用Swagger
@EnableSwagger2
@Configuration
public class SwaggerConfiguration {

    // controller接口所在的包
    @Value("${swagger.basePackage}")
    private String basePackage;

    // 当前文档的标题
    @Value("${swagger.title}")
    private String title;

    // 当前文档的详细描述
    @Value("${swagger.description}")
    private String description;

    // 当前文档的版本
    @Value("${swagger.version}")
    private String version;

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage(basePackage))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(title)
                .description(description)
                .version(version)
                // 参数分别是:作者昵称、作者网站、作者邮箱
                .contact(new Contact("如我西沉", "http://qkongtao.cn/", "******@qq.com"))
                .build();
    }

}

4. 配置Modler对象

不进行配置也可以,Swagger会根据对象名进行自动生成

package cn.kt.springboot_cache.domain;

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

import java.io.Serializable;

@ApiModel(value="员工对象",description="员工对象Employee")
public class Employee implements Serializable {

    @ApiModelProperty(value="员工ID",name="id",example="1")
    private Integer id;
    @ApiModelProperty(value="员工姓名",name="lastName",example="路飞")
    private String lastName;
    @ApiModelProperty(value="员工邮箱",name="email",example="lufei@qq.com")
    private String email;
    @ApiModelProperty(value="员工性别",name="gender",example="男")
    private String gender;
    @ApiModelProperty(value="员工部门编号",name="dId",example="1")
    private Integer dId;
	/*  省略get、set、构造方法  */
}

5. 编写controller层接口

不进行配置也可以,Swagger会根据方法名进行自动生成,但是接口建议配置,添加自己的接口文档说明。
本次测试使用上一篇缓存项目的接口

package cn.kt.springboot_cache.controller;

import cn.kt.springboot_cache.domain.Employee;
import cn.kt.springboot_cache.service.EmployeeService;
import io.swagger.annotations.Api;
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.RestController;

/**
 * @author tao
 * @date 2021-09-20 10:26
 * 概要:
 */

@RestController
@Api(tags = "演示缓存类", description = "EmployeeController相关描述")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @GetMapping("/emp/{id}")
    @ApiOperation(value = "查询员工", notes = "方法的注意事项和备注", nickname = "tao", consumes = "text/html")
    public Employee getEmployee(@PathVariable("id") Integer id) {
        Employee emp = employeeService.getEmp(id);
        return emp;
    }

    @GetMapping("/emp")
    @ApiOperation("新增员工")
    public Employee update(Employee employee) {
        Employee emp = employeeService.updateEmp(employee);

        return emp;
    }

    @GetMapping("/delemp")
    @ApiOperation("删除员工")
    public String deleteEmp(Integer id) {
        employeeService.deleteEmp(id);
        return "success";
    }

    @GetMapping("/emp/lastname/{lastName}")
    @ApiOperation("根据名字查询员工")
    public Employee getEmpByLastName(@PathVariable("lastName") String lastName) {
        return employeeService.getEmpByLastName(lastName);
    }
}

6. 测试效果

访问地址:项目链接/swagger-ui.html
默认项目的地址是 http://localhost:8080/swagger-ui.html

  1. Swagger界面
    在这里插入图片描述

  2. 接口详细说明
    在这里插入图片描述

  3. 点击Try out进行接口测试
    在这里插入图片描述

Swagger常用注解

1. 用于controller类

@Api():用于类;表示标识这个类是swagger的资源
参数:
tags–表示说明 (tags如果有多个值,会生成多个list)
value–也是说明,可以使用tags替代
description–接口的描述

使用方法:

	@RestController
	@Api(tags = "演示缓存类", description = "EmployeeController相关描述")
	public class EmployeeController {
	
	}

效果图:
在这里插入图片描述

2. 用于接口方法上(对接口方法的说明)

@ApiOperation() 用于方法;表示一个http请求的操作
value用于方法描述
notes用于提示内容
tags可以重新分组(视情况而用)
@ApiParam() 用于方法中要接收的参数,字段说明;表示对参数的添加元数据(说明或是否必填等)
name–参数名
value–参数说明
required–是否必填

使用方法:

	 @GetMapping("/emp/lastname/{lastName}")
	    @ApiOperation("根据名字查询员工")
	    public Employee getEmpByLastName(@PathVariable("lastName") @ApiParam(name = "lastName", value = "用户名", required = true) String lastName) {
	        return employeeService.getEmpByLastName(lastName);
	    }

效果图:
在这里插入图片描述

3. 用于Model实体类

@ApiModel()用于类 ;表示对类进行说明,用于参数用实体类接收
value–表示对象名
description–描述
都可省略
@ApiModelProperty()用于方法,字段; 表示对model属性的说明或者数据操作更改
value–字段说明
name–重写属性名字
dataType–重写属性类型
required–是否必填
example–举例说明
hidden–隐藏

使用方法:

	@ApiModel(value="员工对象",description="员工对象Employee")
	public class Employee implements Serializable {
	
	    @ApiModelProperty(value="员工ID",name="id",example="1")
	    private Integer id;
	    @ApiModelProperty(value="员工姓名",name="lastName",example="路飞")
	    private String lastName;
	    @ApiModelProperty(value="员工邮箱",name="email",example="lufei@qq.com")
	    private String email;
	    @ApiModelProperty(value="员工性别",name="gender",example="男")
	    private String gender;
	    @ApiModelProperty(value="员工部门编号",name="dId",example="1")
	    private Integer dId;
	}

效果图:
在这里插入图片描述

4. 用于接口方法上(对要提供的参数说明)

@ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam

@ApiImplicitParam() 用于方法
表示单独的请求参数
name–参数ming
value–参数说明
dataType–数据类型
paramType–参数类型
example–举例说明

使用方法:

	@GetMapping("/emp")
    @ApiOperation("新增员工")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id", dataType = "long", paramType = "query", example = "索隆"),
            @ApiImplicitParam(name = "lastName", value = "用户名", dataType = "string", paramType = "query", example = "索隆"),
            @ApiImplicitParam(name = "email", value = "用户邮箱", dataType = "string", paramType = "query", example = "suolong@qq.com")})

    public Employee update(Employee employee) {
        Employee emp = employeeService.updateEmp(employee);
        return emp;
    }

效果图:
在这里插入图片描述

5. 用于类或者方法上

@ApiIgnore()用于类或者方法上,可以不被swagger显示在页面上
比较简单, 这里不做举例

小结:Swagger提供的注解功能还是很丰富的,但在具体开发中如果全部都要去使用还是挺麻烦的,所以怎么使用,如何使用,还是看开发实际情况吧。

集成Swagger-Bootstrap-UI

SpringBoot集成Swagger后,除了可以时候原始风格的API接口界面,还可以集成其他风格的界面:如页面更清爽的Swagger-Bootstrap-UI和knife4j-spring-ui。

该开源项目GitHub地址:https://github.com/xiaoymin/Swagger-Bootstrap-UI

该开源项目中文文档地址:https://doc.xiaominfo.com/

配置好Swagger后,引入依赖即集成成功
老版本引用

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>swagger-bootstrap-ui</artifactId>
    <version>1.9.6</version>
</dependency>

新版本引用

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-ui</artifactId>
    <version>2.0.9</version>
</dependency>

效果展示
访问新UI的的链接:http://localhost:8080/doc.html

  1. 首页
    在这里插入图片描述
  2. 实体类说明
    在这里插入图片描述
  3. 可导出接口文档
    在这里插入图片描述
  4. 接口详情
    在这里插入图片描述
  5. 接口测试在这里插入图片描述
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不愿意做鱼的小鲸鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值