SpringBoot项目中Swagger的配置和使用
一、概述
Swagger是一个规范、完整的框架,用于生成、描述、调用和可视化Restful风格的Web服务。使用Swagger可以使前端和后端人员实时的进行接口查看和协调。也可对相关的接口进行测试。
二、集成Swagger
1、创建基于Maven的项目,结构目录如下
2、添加swagger的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.3.4.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.whw</groupId>
<artifactId>swagger</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>swagger</name>
<description>Demo project for Spring Boot Swagger</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--Swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<exclusions>
<!--swagger2.92默认依赖1.5.0版本的models和annotations
排除掉此版本,引入一个其他版本,不让项目启动时未报Illegal DefaultValue null for parameter type integer的警告-->
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</exclusion>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
</exclusion>
</exclusions>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.5.22</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.22</version>
</dependency>
<!--Swagger-UI-->
<!--访问路径:http://localhost:8080/swagger-ui.html-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!--swaggerui 几个自定义界面方便查看接口-->
<!--访问路径:http://localhost:8080/doc.html-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.5</version>
</dependency>
<!--访问路径:http://localhost:8080/document.html-->
<!--<dependency>
<groupId>com.zyplayer</groupId>
<artifactId>swagger-mg-ui</artifactId>
<version>1.0.6</version>
</dependency>-->
<!--访问路径:http://localhost:8080/docs.html-->
<!-- <dependency>
<groupId>com.github.caspar-chen</groupId>
<artifactId>swagger-ui-layer</artifactId>
<version>1.1.3</version>
</dependency>-->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3、自定义响应状态码枚举:RestResponseCode
package com.whw.swagger.config;
/**
* @描述 自定义响应状态码枚举
**/
public enum RestResponseCode {
SUCCESS(200, "success"),
FAIL(300, "fail"),
BODY_NOT_MATCH(400, "请求的数据格式不符!"),
SIGNATURE_NOT_MATCH(401, "请求的数字签名不匹配!"),
NOT_FOUND(404, "未找到该资源!"),
INTERNAL_SERVER_ERROR(500, "服务器内部错误!"),
SERVER_BUSY(503, "服务器正忙,请稍后再试!"),
UNDEFINED_ERROR(1000, "未知错误!"),
NOTE(1001, "自定义提示!"),
PARAMETERERROR(409, "参数错误!"),
NOTLOGIN(402, "登陆错误!"),
EXPIRE(1002, "Session过期了");
int code;
String msg;
RestResponseCode(int code, String msg) {
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
4、新建Swagger配置类:SwaggerConfig
package com.whw.swagger.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
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.Arrays;
import java.util.List;
@Configuration
@EnableSwagger2//开启Swagger
public class SwaggerConfig {
/*配置多个分组,只需要配置多个Docket即可,设置不同分组扫描不同的包*/
@Bean
public Docket docketA() {
return new Docket(DocumentationType.SWAGGER_2).groupName("A");
}
@Bean
public Docket docketB() {
return new Docket(DocumentationType.SWAGGER_2).groupName("B");
}
@Bean
public Docket docketC() {
return new Docket(DocumentationType.SWAGGER_2).groupName("C");
}
//配置Swagger的bean实例
@Bean
public Docket docket(Environment environment) {
List<ResponseMessage> responseMessageList = new ArrayList<>();
Arrays.stream(RestResponseCode.values()).forEach(stateCodeEnum ->
{
responseMessageList.add(
/*new ResponseMessageBuilder()
.code(stateCodeEnum.getCode())
.message(stateCodeEnum.getMsg())
.responseModel(new ModelRef(stateCodeEnum.getMsg()))
.build());//这种形式swagger提示自定义返回msg找不到*/
new ResponseMessageBuilder()
.code(stateCodeEnum.getCode())
.message(stateCodeEnum.getMsg())
.build());
});
//设置要显示的Swagger环境
Profiles profiles = Profiles.of("dev");
//获取项目环境:是生产环境还是发布环境
boolean flag = environment.acceptsProfiles(profiles);
return new Docket(DocumentationType.SWAGGER_2)
//添加全局状态码
.globalResponseMessage(RequestMethod.GET, responseMessageList)
.globalResponseMessage(RequestMethod.POST, responseMessageList)
.globalResponseMessage(RequestMethod.PUT, responseMessageList)
.globalResponseMessage(RequestMethod.DELETE, responseMessageList)
.apiInfo(apiInfo())
.groupName("大华子")
.enable(flag)//是否启用swagger,如果为false则swagger不能再浏览器中访问
.select()//通过select()方法配置扫描接口,RequestHandlerSelectors配置如何扫描接口
//指定扫描的api包
.apis(RequestHandlerSelectors.basePackage("com.whw.swaggerdemo.controller"))
//.paths(PathSelectors.ant("/sys/**"));//通过paths()方法配置扫描接口,PathSelectors配置如何扫描接口
.build();
/*
* RequestHandlerSelectors除了设置basePackage外还可以配置其他方式扫描接口
* any():扫描所有,项目中的所有接口都会被扫描到
*
* none():不扫描接口
*
* 通过方法上的注解扫描,如withMethodAnnotation(GetMapping.class)只扫描get请求
* withMethodAnnotation(final Class<? extends Annotation> annotation):
*
* // 通过类上的注解扫描,如.withClassAnnotation(Controller.class)只扫描有controller注解的类中的接口
* withClassAnnotation(final Class<? extends Annotation> annotation)
*
* basePackage(final String basePackage):根据包路径扫描接口
* */
/*
* PathSelectors的可选值有以下几种
* any():任何请求都扫描
* none():任何请求都不扫描
* regex(final String pathRegex):通过正则表达式控制
* ant(final String antPattern):通过ant()控制
* */
}
private ApiInfo apiInfo() {
Contact contact = new Contact("大华子", "", "xxxxxxxxx@qq.com");
return new ApiInfo(
"大华子的SwaggerAPI文档",
"不断学习,不断进步",
"1.0",
"urn:tos",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList());
}
}
5、新建用户实体类:User
package com.whw.swagger.pojo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel("用户实体类")
public class User {
@ApiModelProperty("id")
private Integer id;
@ApiModelProperty("用户名")
public String username;
@ApiModelProperty("密码")
public String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
6、新建用户操作控制器:SysUserController
package com.whw.swagger.controller;
import com.whw.swagger.pojo.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@Api(tags = "用户操作模块API")//作用在模块API类上,对API模块进行说明
@RestController(value = "/sys/user/")
public class SysUserController {
@ApiOperation("添加用户接口")//作用在API方法上,对操作进行说明
@PostMapping(value = "/add")
public String add(User user) {
return "success";
}
@ApiOperation("根据ID查询用户")
@GetMapping(value = "/user")
//作用在参数上,对参数进行说明
public User find(
@ApiParam(name = "用户ID", required = true) Integer id) {
return new User();
}
@ApiOperation("更新用户")
@PostMapping(value = "/update")
public String update(
@ApiParam("用户对象") User user) {
return "success";
}
@ApiOperation("删除用户")
@GetMapping(value = "/delete")
public Integer delete(@ApiParam("用户ID") Integer id) {
return 1;
}
}
7、application.properties中配置
spring.profiles.active=dev
8、访问默认UI风格Swagger
地址:http://localhost:8081/swagger-ui.html
9、访问bootstrap的UI风格Swagger
地址:http://localhost:8081/doc.html
10、项目demo下载地址
链接:https://pan.baidu.com/s/1WvZ0K_u6TKcv08QPPLI-8A
提取码:5ypy