1)简介:
作为后端开放人员,最烦的事就是自己写接口文档和别人没有写接口文档,不管是前端还是后端开发,多多少少都会被接口文档所折磨,前端会抱怨后端没有及时更新接口文档,而后端又会觉得编写接口文档太过麻烦。
Swagger 可以较好的解决接口文档的交互问题,以一套标准的规范定义接口以及相关的信息,就能做到生成各种格式的接口文档,生成多种语言和客户端和服务端的代码,以及在线接口调试页面等等。只需要更新 Swagger 描述文件,就能自动生成接口文档,做到前端、后端联调接口文档的及时性和便利性。
Swagger是一个规范且完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。
2)优势:
-
支持 API 自动生成同步的在线文档:使用 Swagger 后可以直接通过代码生成文档,不再需要自己手动编写接口文档了,对程序员来说非常方便,可以节约写文档的时间去学习新技术。
-
提供 Web 页面在线测试 API:光有文档还不够,Swagger 生成的文档还支持在线测试。参数和格式都定好了,直接在界面上输入参数对应的值即可在线测试接口。
3)SpringBoot整合Swagger
1.pom.xml的properties便签中加入以下代码
<properties><swagger.versiion>3.0.0</swagger.versiion></properties>
2.在pom.xml的dependencies标签中添加Swagger依赖
<dependency><groupId>io.springfox</groupId><artifactId>springfox-boot-starter</artifactId><version>${swagger.versiion}</version></dependency>
3.创建config包,在config包下添加Swagger配置类
package com.cqh.config;import io.swagger.annotations.ApiOperation;
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.oas.annotations.EnableOpenApi;
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;@Configuration
//@EnableSwagger2
@EnableOpenApi
public class SwaggerConfig {@Beanpublic Docket productApi() {return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())// 为api选择启动生成器.select()// 指定要生成api文档的根包.apis(RequestHandlerSelectors.basePackage("com.cqh.controller")) //添加ApiOperiation注解的被扫描.paths(PathSelectors.any()).build();}private ApiInfo apiInfo() {return new ApiInfoBuilder()// 文档标题.title("项目测试")// 简介.description("测试练习")// 作者信息:作者姓名、作者地址、作者邮箱.contact(new Contact("cqh","https://www.cqh.com","666666.@qq.com")).version("1.0").build();}}
浏览器访问http://localhost:8080/swagger-ui/#/
如果出现
pom.xml中 加上
<dependency><groupId>org.springframework.plugin</groupId><artifactId>spring-plugin-core</artifactId><version>2.0.0.RELEASE</version></dependency>
4)添加文档内容
在完成了上述配置后,其实已经可以生产文档内容,但是这样的文档主要针对请求本身,描述的主要来源是函数的命名,通常需要自己增加一些说明来丰富文档内容。
Swagger使用的注解及其说明:
@Api:用在类上,说明该类的作用。
@ApiOperation:注解来给API增加方法说明。
@ApiParam:定义在参数上
@ApiResponses:用于表示一组响应
@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息 l code:数字,例如400 l message:信息,例如"请求参数没填好" l response:抛出异常的类
@ApiModel:描述一个Model的信息
l @ApiModelProperty:描述一个model的属性
案例
1.数据库导入
# Host: localhost (Version 5.7.23-log)
# Date: 2023-12-05 13:26:01
# Generator: MySQL-Front 6.0 (Build 2.20)#
# Structure for table "account_info"
#CREATE TABLE `account_info` (`account` varchar(11) NOT NULL COMMENT '用户账号,主键',`acc_name` varchar(50) NOT NULL COMMENT '用户姓名',`password` varchar(255) NOT NULL COMMENT '鐢ㄦ埛瀵嗙爜锛岄粯璁ゆ墜鏈哄彿鍚?浣?',`acc_phone` varchar(11) NOT NULL COMMENT '手机号11位,唯一',`is_enable` tinyint(1) NOT NULL COMMENT '是否启用(1:启用,0:未启用)',`create_time` datetime NOT NULL COMMENT '创建时间',`update_time` datetime NOT NULL COMMENT '更新时间',PRIMARY KEY (`account`),UNIQUE KEY `uk_phone` (`acc_phone`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;#
# Data for table "account_info"
#INSERT INTO `account_info` VALUES ('YZ0001','admin','92159b1631dae48aa523875174e3ea60','13811345670',1,'2023-08-18 11:34:28','2023-08-18 11:34:28'),('YZ0002','admin','986fa807bbe0c721702868bae6ef8a33','13811345679',1,'2023-08-18 11:34:38','2023-08-18 11:34:38'),('YZ0003','admin2','7d839f278639a38b2ba83ad67ab836a2','13811345677',1,'2023-08-18 14:46:05','2023-08-18 14:46:05'),('YZ0004','admin2','35ea60fd301a3895245aff0ca4947d9e','13811345674',1,'2023-08-18 15:03:12','2023-08-18 15:03:12');
2.pom.xml配置依赖导入
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.4.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.cqh</groupId><artifactId>springboot1129</artifactId><version>0.0.1-SNAPSHOT</version><name>springboot1129</name><description>springboot1129</description><properties><java.version>8</java.version><swagger.versiion>3.0.0</swagger.versiion></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>io.springfox</groupId><artifactId>springfox-boot-starter</artifactId><version>${swagger.versiion}</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><dependency><groupId>org.springframework.plugin</groupId><artifactId>spring-plugin-core</artifactId><version>2.0.0.RELEASE</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
3.数据库连接配置
spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://127.0.0.1:3306/ssmlmh?serverTimezone=Asia/Shanghai&characterEncoding=utf-8username: rootpassword: rootmybatis:mapper-locations: classpath*:mapper/*.xmltype-aliases-package: com.cqh.entity
4.创建实体类
package com.cqh.entity;import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;@Data
@ApiModel(value = "AccountInfoVo",description = "人员账号信息"
)
public class AccountInfo {@ApiModelProperty(value = "登录账号")private String account;@ApiModelProperty(value = "人员名称")private String accName;@ApiModelProperty(value = "登陆密码")private String password;public String getAccount() {return account;}public void setAccount(String account) {this.account = account;}public String getAccName() {return accName;}public void setAccName(String accName) {this.accName = accName;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}@Overridepublic String toString() {return "AccountInfo{" +"account='" + account + '\'' +", accName='" + accName + '\'' +", password='" + password + '\'' +'}';}
}
5. swagger配置类也不能忘记
package com.cqh.config;import io.swagger.annotations.ApiOperation;
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.oas.annotations.EnableOpenApi;
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;@Configuration
//@EnableSwagger2
@EnableOpenApi
public class SwaggerConfig {@Beanpublic Docket productApi() {return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())// 为api选择启动生成器.select()// 指定要生成api文档的根包.apis(RequestHandlerSelectors.basePackage("com.cqh.controller")) //添加ApiOperiation注解的被扫描.paths(PathSelectors.any()).build();}private ApiInfo apiInfo() {return new ApiInfoBuilder()// 文档标题.title("项目测试")// 简介.description("测试练习")// 作者信息:作者姓名、作者地址、作者邮箱.contact(new Contact("cqh","https://www.cqh.com","666666.@qq.com")).version("1.0").build();}}
6.mapper配置文件
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.cqh.mapper.AccountInfoMapper"><select id="selectAll" parameterType="String" resultType="com.cqh.entity.AccountInfo">SELECT account,acc_Name AS accName,password FROM account_info</select><select id="selectByName" parameterType="String" resultType="com.cqh.entity.AccountInfo">SELECT account, acc_Name AS accName, passwordFROM account_infoWHERE acc_name LIKE CONCAT('%', #{accName}, '%');</select>
</mapper>
7.mapper接口
package com.cqh.mapper;import com.cqh.entity.AccountInfo;import java.util.List;public interface AccountInfoMapper {List<AccountInfo> selectAll();List<AccountInfo> selectByName(String accName);
}
8.service层接口
package com.cqh.service;import com.cqh.entity.AccountInfo;import java.util.List;public interface AccountService {List<AccountInfo> selectAll();
//改一下返回类型List<AccountInfo> selectByName(String accName);
}
9.service实现类
package com.cqh.service.impl;import com.cqh.entity.AccountInfo;
import com.cqh.mapper.AccountInfoMapper;
import com.cqh.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class AccountServiceImpl implements AccountService {@Autowiredprivate AccountInfoMapper accountInfoMapper;@Overridepublic List<AccountInfo> selectAll() {return accountInfoMapper.selectAll();}@Overridepublic List<AccountInfo> selectByName(String accName) {return accountInfoMapper.selectByName(accName);}
}
10.控制器层
package com.cqh.controller;import com.cqh.entity.AccountInfo;
import com.cqh.service.AccountService;import io.swagger.annotations.*;
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;@RestController
@Api(value = "积分等级管理",tags = {"人员信息"})
public class AccountInfoController {@Autowiredprivate AccountService accountService;@GetMapping("/getByName/{accName}")@ApiOperation("根据账号查询人员信息")public List<AccountInfo> getById(@ApiParam(value = "要查询的账号",required = true,example = "1") @PathVariable String accName){return accountService.selectByName(accName);}
}
11.浏览器访问
http://localhost:8080/swagger-ui/#/
12.找到要测试的方法
13.点击ty it out
14.输入要查询的类容
15.点击执行
16.查看执行结果