一、概述
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