Swagger使用

一、简介

https://swagger.io/tools/swagger-ui/

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。

作用

  • 接口的文档在线自动生成
  • 功能测试

Swagger是一组开源项目,其中主要要项目如下

  •   Swagger-tools:提供各种与Swagger进行集成和交互的工具。例如模式检验、Swagger 1.2文档转换成Swagger 2.0文档等功能。
  •  Swagger-core: 用于Java/Scala的的Swagger实现。与JAX-RS(Jersey、Resteasy、CXF...)、Servlets和Play框架进行集成。
  • Swagger-js: 用于JavaScript的Swagger实现。
  • Swagger-node-express: Swagger模块,用于node.js的Express web应用框架。
  • Swagger-ui:一个无依赖的HTML、JS和CSS集合,可以为Swagger兼容API动态生成优雅文档。
  • Swagger-codegen:一个模板驱动引擎,通过分析用户Swagger资源声明以各种语言生成客户端代码

二、测试Demo

(1)创建项目

创建一个spring boot项目

(2)依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.1.7.RELEASE</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.example</groupId>
  12. <artifactId>swagger</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>swagger</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. </properties>
  19. <dependencies>
  20. <!--Swagger依赖-->
  21. <dependency>
  22. <groupId>io.springfox</groupId>
  23. <artifactId>springfox-swagger2</artifactId>
  24. <version>2.9.2</version>
  25. </dependency>
  26. <dependency>
  27. <groupId>io.springfox</groupId>
  28. <artifactId>springfox-swagger-ui</artifactId>
  29. <version>2.9.2</version>
  30. </dependency>
  31. <!--hibernate校验依赖 -->
  32. <dependency>
  33. <groupId>org.hibernate</groupId>
  34. <artifactId>hibernate-validator</artifactId>
  35. <version>6.0.16.Final</version>
  36. </dependency>
  37. <dependency>
  38. <groupId>org.springframework.boot</groupId>
  39. <artifactId>spring-boot-starter</artifactId>
  40. </dependency>
  41. <dependency>
  42. <groupId>org.springframework.boot</groupId>
  43. <artifactId>spring-boot-starter-web</artifactId>
  44. </dependency>
  45. <dependency>
  46. <groupId>com.fasterxml.jackson.core</groupId>
  47. <artifactId>jackson-annotations</artifactId>
  48. <version>2.9.0</version>
  49. </dependency>
  50. </dependencies>
  51. <build>
  52. <plugins>
  53. <plugin>
  54. <groupId>org.springframework.boot</groupId>
  55. <artifactId>spring-boot-maven-plugin</artifactId>
  56. </plugin>
  57. </plugins>
  58. </build>
  59. </project>

(3)application.properties配置

  1. #https://blog.csdn.net/z_k_h/article/details/81875828(为啥配置)
  2. logging.level.io.swagger.models.parameters.AbstractSerializableParameter=error

(4)Swagger2配置类

  1. package cn.zzq.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.ComponentScan;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  6. import springfox.documentation.builders.ApiInfoBuilder;
  7. import springfox.documentation.builders.PathSelectors;
  8. import springfox.documentation.builders.RequestHandlerSelectors;
  9. import springfox.documentation.service.ApiInfo;
  10. import springfox.documentation.service.Contact;
  11. import springfox.documentation.spi.DocumentationType;
  12. import springfox.documentation.spring.web.plugins.Docket;
  13. import springfox.documentation.swagger2.annotations.EnableSwagger2;
  14. @EnableSwagger2
  15. @ComponentScan(basePackages = {"cn.zzq.controller"})
  16. @Configuration
  17. public class SwaggerConfig implements WebMvcConfigurer {
  18. @Bean
  19. public Docket createRestApi() {
  20. return new Docket(DocumentationType.SWAGGER_2)
  21. .apiInfo(apiInfo())
  22. .select()
  23. .apis(RequestHandlerSelectors.any())
  24. .paths(PathSelectors.any())
  25. .build();
  26. }
  27. private ApiInfo apiInfo() {
  28. return new ApiInfoBuilder()
  29. .title("《SwaggerDemo的演示案例--》")//标题
  30. .description("description:项目摘要")//描述
  31. .termsOfServiceUrl("http://www.google.com.hk")//(不可见)条款地址,公司内部使用的话不需要配
  32. .contact(new Contact("Devil", "http://www.google.com.hk", "xx@qq.com"))//作者信息
  33. .version("2.9.2")//版本号
  34. .build();
  35. }
  36. }

如上代码所示,通过createRestApi函数创建Docket的Bean之后,apiInfo()用来创建该Api的基本信息(这些基本信息会展现在文档页面中)

(5)JsonResult

  1. package cn.zzq.bean;
  2. public class JsonResult {
  3. private String code;
  4. private String msg;
  5. private Object data;
  6. private int totalPage;
  7. public String getCode() {
  8. return code;
  9. }
  10. public void setCode(String code) {
  11. this.code = code;
  12. }
  13. public String getMsg() {
  14. return msg;
  15. }
  16. public void setMsg(String msg) {
  17. this.msg = msg;
  18. }
  19. public Object getData() {
  20. return data;
  21. }
  22. public void setData(Object data) {
  23. this.data = data;
  24. }
  25. public int getTotalPage() {
  26. return totalPage;
  27. }
  28. public void setTotalPage(int totalPage) {
  29. this.totalPage = totalPage;
  30. }
  31. public void success() {
  32. this.code = "200";
  33. this.msg = "请求成功!";
  34. }
  35. public void success(Object data) {
  36. success();
  37. this.data = data;
  38. }
  39. public void success(String msg) {
  40. success();
  41. this.msg = msg;
  42. }
  43. public void failure() {
  44. this.code = "500";
  45. this.msg = "请求失败!";
  46. }
  47. public void failure(String msg) {
  48. failure();
  49. this.msg = msg;
  50. }
  51. public void setFailure(Integer code, String msg) {
  52. this.code = code + "";
  53. this.msg = msg;
  54. }
  55. }

(6)User

  1. package cn.zzq.bean;
  2. import io.swagger.annotations.ApiModelProperty;
  3. import javax.validation.constraints.*;
  4. public class User {
  5. @ApiModelProperty(value="用户名")
  6. @NotEmpty(message="姓名不能为空")
  7. private String name;
  8. @ApiModelProperty(value="密码")
  9. @NotEmpty(message="密码不能为空")
  10. private String password;
  11. @ApiModelProperty(value="性别")
  12. @NotEmpty(message="性别不能为空")
  13. private String gender;
  14. @ApiModelProperty(value="年龄")
  15. @NotNull(message="年龄不能为空")
  16. @Min(value=18,message="必须年满18岁!")
  17. @Max(value=30,message="年龄不能大于30岁!")
  18. private Integer age;
  19. public String getName() {
  20. return name;
  21. }
  22. public void setName(String name) {
  23. this.name = name;
  24. }
  25. public String getPassword() {
  26. return password;
  27. }
  28. public void setPassword(String password) {
  29. this.password = password;
  30. }
  31. public String getGender() {
  32. return gender;
  33. }
  34. public void setGender(String gender) {
  35. this.gender = gender;
  36. }
  37. public Integer getAge() {
  38. return age;
  39. }
  40. public void setAge(Integer age) {
  41. this.age = age;
  42. }
  43. }

(7)UserController

  1. package cn.zzq.controller;
  2. import cn.zzq.bean.JsonResult;
  3. import cn.zzq.bean.User;
  4. import io.swagger.annotations.*;
  5. import org.springframework.http.HttpStatus;
  6. import org.springframework.util.StringUtils;
  7. import org.springframework.validation.BindingResult;
  8. import org.springframework.validation.FieldError;
  9. import org.springframework.web.bind.annotation.*;
  10. import javax.validation.Valid;
  11. import java.util.ArrayList;
  12. import java.util.List;
  13. @Api(value="User的相关信息接口",description="User的相关信息接口", protocols="http")
  14. @RestController
  15. public class UserController {
  16. @ApiOperation(notes="获取所有user,无需参数",value="获取所有user", httpMethod = "GET")
  17. @GetMapping("/getAll")
  18. public Object getAll(){
  19. //查出的所有部门信息
  20. List<User> list = new ArrayList<User>();
  21. User user = new User();
  22. user.setAge(23);
  23. user.setGender("男");
  24. user.setName("zhangsan");
  25. user.setPassword("123456");
  26. list.add(user);
  27. return list;
  28. }
  29. @ApiOperation(value="获取单个user", notes="传入json格式",httpMethod = "POST")
  30. @PostMapping("/getOne")
  31. public Object getOne(@RequestBody @Valid User user, BindingResult result){
  32. JsonResult jsonResult = new JsonResult();
  33. if(result.hasErrors()){
  34. List<FieldError> fieldErrors = result.getFieldErrors();
  35. for(int i=0;i<fieldErrors.size();i++){
  36. //控制台打印不符合校验的字段名和错误提示
  37. System.out.println("error field is :"+fieldErrors.get(i).getField()+",message is :"+fieldErrors.get(i).getDefaultMessage());
  38. String errorMsg = fieldErrors.get(i).getDefaultMessage();
  39. if(!StringUtils.isEmpty(errorMsg)){
  40. jsonResult.setFailure(HttpStatus.BAD_REQUEST.value(),errorMsg);
  41. return jsonResult;
  42. }
  43. }
  44. }
  45. jsonResult.setFailure(HttpStatus.OK.value(),HttpStatus.OK.getReasonPhrase());
  46. return jsonResult;
  47. }
  48. @ApiOperation(value="根据名称获取user",notes="传入json格式")
  49. @ApiResponses({
  50. @ApiResponse(code = 200, message = "请求成功"),
  51. @ApiResponse(code = 500, message = "请求失败,后台服务出现异常"),
  52. @ApiResponse(code = 401, message = "代表此操作无权限访问"),
  53. @ApiResponse(code = 400, message = "表示请求参数错误"),
  54. })
  55. @PostMapping("/getOneByName")
  56. public Object getOneByName(@ApiParam(value = "用户名", required = true) @RequestBody String name){
  57. User u = new User();
  58. u.setAge(23);
  59. u.setGender("男");
  60. u.setName(name);
  61. u.setPassword("123456");
  62. return u;
  63. }
  64. @ApiOperation(value="修改用户",notes="参数非json格式", httpMethod="POST")
  65. @ApiImplicitParams({
  66. @ApiImplicitParam(paramType="query", name = "name", value = "用户名", required = true, dataType = "String"),
  67. @ApiImplicitParam(paramType="query", name = "possword", value = "密码", required = true, dataType = "String")
  68. })
  69. @PostMapping("/update")
  70. public Object update(String name,String possword){
  71. User u = new User();
  72. u.setAge(23);
  73. u.setGender("男");
  74. u.setName(name);
  75. u.setPassword(possword);
  76. return u;
  77. }
  78. }

(7)启动类

  1. package cn.zzq;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import springfox.documentation.swagger2.annotations.EnableSwagger2;
  5. @SpringBootApplication
  6. public class SwaggerApplication {
  7. public static void main(String[] args) {
  8. SpringApplication.run(SwaggerApplication.class, args);
  9. }
  10. }

(8)效果

http://localhost:8080/swagger-ui.html

三、Swagger使用的注解及其说明

@Api: 用在类上,说明该类的作用。

@ApiOperation:注解来给API增加方法说明。

@ApiImplicitParams : 用在方法上包含一组参数说明。

@ApiImplicitParam:用来注解来给方法入参增加说明。

@ApiResponses:用于表示一组响应

@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息

    l   code:数字,例如400

    l   message:信息,例如"请求参数没填好"

    l   response:抛出异常的类   

@ApiModel:描述一个Model的信息(一般用在请求参数无法使用@ApiImplicitParam注解进行描述的时候)

    l   @ApiModelProperty:描述一个model的属性

注意:@ApiImplicitParam的参数说明:

paramType:指定参数放在哪个地方

header:请求参数放置于Request Header,使用@RequestHeader获取

		<p>query:请求参数放置于请求地址,使用@RequestParam获取</p>

		<p>path:(用于restful接口)--&gt;请求参数的获取:@PathVariable</p>

		<p>body:(不常用)</p>

		<p>form(不常用)</p>
		</td>
	</tr><tr><td>
		<p>name:参数名</p>
		</td>
		<td>
		<p>&nbsp;</p>
		</td>
	</tr><tr><td>
		<p>dataType:参数类型</p>
		</td>
		<td>
		<p>&nbsp;</p>
		</td>
	</tr><tr><td>
		<p>required:参数是否必须传</p>
		</td>
		<td>
		<p>true | false</p>
		</td>
	</tr><tr><td>
		<p>value:说明参数的意思</p>
		</td>
		<td>
		<p>&nbsp;</p>
		</td>
	</tr><tr><td>
		<p>defaultValue:参数的默认值</p>
		</td>
		<td>
		<p>&nbsp;</p>
		</td>
	</tr></tbody></table></div><p>swagger-bootstrap-ui 访问权限控制&nbsp;<a href="https://blog.csdn.net/niugang0920/article/details/90229403">https://blog.csdn.net/niugang0920/article/details/90229403</a></p>
                                </div>
posted @ 2020-07-07 16:58  edda_huang  阅读(206)  评论(0编辑  收藏  举报