历经 14 天自定义 3 个注解解决项目的 3 个 Swagger 难题

1,909 阅读22分钟

文章目录 14 天自定义 3 个注解扩展 Swagger 的 3 个功能的经历前言(一)本文针对的小伙伴(二)通过本文能了解或者学到什么一、第一部分:基础 (可跳过)(一)swagger 简介 1、springfox-swa......

(一)本文针对的小伙伴

点开此文章的小伙伴们请注意了,本片文章针对的是对 Swagger 有一定基础的小伙伴;

你应该具备或者已经具备的:

  • 1、有过 Swagger 的使用经历;
  • 2、了解过 Swagger,动手去集成过 SpringBoot;
  • 3、对自定义注解解决业务需求有想迫切了解的兴趣。
  • 4、…。

(二)通过本文能了解或者学到什么

本篇文章是我通过大量的实践,摸索、查资料、Debug 源代码一步一步的摸索出来的,整理一份比较详细的资料,以便也有利于他人,少走弯路。

通过本文你将会:

  • 1、了解到 SpringBoot 项目中如何自定义注解并且使用;
  • 2、掌握如何扩展 Swagger 的功能,并成功的用在项目上;
  • 3、了解到自定义注解的流程,以及如果应用的过程;
  • 4、少走一些坑。

img

(一)swagger 简介

swagger 确实是个好东西。

为什么是个好东西呢?

img

因为:

  • 1、可以跟据业务代码自动生成相关的 api 接口文档,尤其用于 restful 风格中的项目;
  • 2、开发人员几乎可以不用专门去维护 rest api,这个框架可以自动为你的业务代码生成 restfut 风格的 api;
  • 3、而且还提供相应的测试界面,自动显示 json 格式的响应。
  • 4、大大方便了后台开发人员与前端的沟通与联调成本。

1、springfox-swagger 简介

鉴于 swagger 的强大功能,java 开源界大牛 spring 框架迅速跟上,它充分利用自已的优势,把 swagger 集成到自己的项目里,整了一个 spring-swagger,后来便演变成 springfox。springfox 本身只是利用自身的 aop 的特点,通过 plug 的方式把 swagger 集成了进来,它本身对业务 api 的生成,还是依靠 swagger 来实现。

关于这个框架的文档,网上的资料比较少,大部分是入门级的简单使用。本人在集成这个框架到自己项目的过程中,遇到了不少坑,为了解决这些坑,我不得不扒开它的源码来看个究竟。此文,就是记述本人在使用 springfox 过程中对 springfox 的一些理解以及需要注意的地方。

2、springfox 大致原理

springfox 的大致原理就是,在项目启动的过程中,spring 上下文在初始化的过程,框架自动跟据配置加载一些 swagger 相关的 bean 到当前的上下文中,并自动扫描系统中可能需要生成 api 文档那些类,并生成相应的信息缓存起来。如果项目 MVC 控制层用的是 springMvc 那么会自动扫描所有 Controller 类,跟据这些 Controller 类中的方法生成相应的 api 文档。

(二)SpringBoot 集成 Swagger

springfox-swagger-ui 依赖并不是必须的,可以使用第三方的 UI,也可以自己写一套前端的 UI 集成进来。

我们就可以使用一个基于 bootstrap 写的 UI。

1、引入相关依赖

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>

截至到目前 2020.9.9 日 springfox-swagger2:2.9.2 的版本主要引入了下面这些依赖:

  • io.swagger:swagger-annotations:1.5.20
  • io.swagger:swagger-models:1.5.20
  • io.springfox:springfox-spi:2.9.2
  • io.springfox:springfox-schema:2.9.2
  • io.springfox:springfox-swagger-common:2.9.2
  • io.springfox:springfox-spring-web:2.9.2
  • com.google.guava:guava:20.0
  • com.fasterxml:classmate:1.3.3
  • org.slf4j:slf4j-api:1.7.24
  • org.springframework.plugin:spring-plugin-core:1.2.0.RELEASE
  • org.springframework.plugin:spring-plugin-metadata:1.2.0.RELEASE
  • org.mapstruct:mapstruct:1.2.0.Final
  • io.springfox:springfox-core:2.9.2
  • net.bytebuddy:byte-buddy:1.8.12

为了页面好看,我们也可以引入这个基于 Bootstrap 的前端 UI:

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    
    <version>2.0.4</version>
</dependency>

默认的 swagger 界面:

img

引入第三方 Bootstrap 编写的 UI:

img

2、配置相关配置文件

@Configuration
@EnableSwagger2
@EnableKnife4j 
public class Swagger2Config {

    @Bean
    public Docket appApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .useDefaultResponseMessages(false) 
                .groupName("知识库")
                .apiInfo(apiInfo())
                .select()

                

            
                
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();

    }



    
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("知识库接口文档")
                .description("该文档主要提供知识库后端的接口 \r\n\n")
                .contact(new springfox.documentation.service.Contact("我们是机器人<----q'(^_^)'p---->业务后台开发组", "https://www.glodon.com/", null))
                .version("0.0.1")
                .build();
    }


}

在这里需要注意的是,需要扫描的位置:

有以下两种方式

.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))

如何使用了第一种,那么就会扫描固定的包下的所有的 Controller 类,会全部自动生成相应的 API 示例,例如下图所示:

好处是只要你在 Controller 控制层的类中定义了某个接口,或者定义了多个接口,就会直接扫描出来。简单方便快捷

有好处的到来,就相当于要带来不好的问题,那么就是:会造成一团乱麻,全部生成的 API,也会很乱。

img

只配置了这些还不够,还需要配置 MVC 模式来显示网页:

@Configuration
public class SwaggerWebMvcConfigurer implements WebMvcConfigurer {
    
    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        
        



        registry.addResourceHandler("doc.html").
                addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**").
                addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

(三)Swagger 常用注解的使用简单归纳

  • 1、@Api
  • 2、@ApiOperation
  • 3、@ApiOperation
  • 4、@ApiImplicitParams、@ApiImplicitParam
  • 5、@ApiResponses、@ApiResponse
  • 6、@ApiModel、@ApiModelProperty
  • 7、 @PathVariable
  • 8、 @RequestParam

1、@APi

描述:

@Api 注解用于标注一个 Controller(Class)。

主要属性

属性描述
valueurl 的路径值
tags如果设置这个值、value 的值会被覆盖
description对 api 资源的描述
basePath基本路径可以不配置
position如果配置多个 Api 想改变显示的顺序位置
producesFor example, “application/json, application/xml”
consumesFor example, “application/json, application/xml”
protocolsPossible values: http, https, ws, wss.
authorizations高级特性认证时配置
hidden配置为 true 将在文档中隐藏

例子

@Controller
@Api(tags = "请求测试API",position = 1)
public class TestController {
    
}

效果:

加上 @Api 注解就代表你这 Controller 允许被 Swagger 相关组件扫描到。

img

2、@ApiOperation

描述:

@ApiOperation 注解在用于对一个操作或 HTTP 方法进行描述。具有相同路径的不同操作会被归组为同一个操作对象。不同的 HTTP 请求方法及路径组合构成一个唯一操作。

主要属性

属性描述
valueurl 的路径值
tags如果设置这个值、value 的值会被覆盖
description对 api 资源的描述
basePath基本路径可以不配置
position如果配置多个 Api 想改变显示的顺序位置
producesFor example, “application/json, application/xml”
consumesFor example, “application/json, application/xml”
protocolsPossible values: http, https, ws, wss.
authorizations高级特性认证时配置
hidden配置为 true 将在文档中隐藏
response返回的对象
responseContainer这些对象是有效的 “List”, “Set” or “Map”.,其他无效
httpMethod“GET”, “HEAD”, “POST”, “PUT”, “DELETE”, “OPTIONS” and “PATCH”
codehttp 的状态码 默认 200
extensions扩展属性

例子

@GetMapping("/get")
@ResponseBody
@ApiOperation(value = "get请求测试",notes = "get请求",position = 1)
public String get(String name){
    JSONObject json = new JSONObject();
    json.put("requestType","getType");
    json.put("name",name);
    return json.toString();
}

效果:

img

3、@ApiParam

描述:

@ApiParam 作用于请求方法上,定义 api 参数的注解。

主要属性

属性描述
name属性名称
value属性值
defaultValue默认属性值
allowableValues可以不配置
required是否属性必填
access不过多描述
allowMultiple默认为 false
hidden隐藏该属性
example举例子

例子

@GetMapping("/get")
@ResponseBody
@ApiOperation(value = "get请求测试",notes = "get请求",position = 1)
public String get(@ApiParam(required = true,value = "name",example = "张三",name = "name") String name){
    JSONObject json = new JSONObject();
    json.put("requestType","getType");
    json.put("name",name);

    return json.toString();
}

效果:

img

img

img

4、@ApiImplicitParams、@ApiImplicitParam

描述:

@ApiImplicitParams:用在请求的方法上,包含一组参数说明@ApiImplicitParam:对单个参数的说明

主要属性

属性描述
name参数名
value参数的说明、描述
required参数是否必须必填
paramType参数放在哪个地方 query --> 请求参数的获取:@RequestParam header --> 请求参数的获取:@RequestHeader path(用于 restful 接口)–> 请求参数的获取:@PathVariable body(请求体)–> @RequestBody User user form(普通表单提交)
dataType参数类型,默认 String,其它值 dataType=“Integer”
defaultValue参数的默认值

例子

@ApiImplicitParams({
    @ApiImplicitParam(name="mobile",value="手机号",required=true,paramType="form"),
    @ApiImplicitParam(name="password",value="密码",required=true,paramType="form"),
    @ApiImplicitParam(name="age",value="年龄",required=true,paramType="form",dataType="Integer")
})
@PostMapping("/login")
public JsonResult login(@RequestParam String mobile, @RequestParam String password,
                        @RequestParam Integer age){
    
    return JsonResult.ok(map);
}

效果:

和上一个一样,就是换了个位置来表达而已。

img

5、@ApiResponses、@ApiResponse

描述:

@ApiResponses、@ApiResponse 进行方法返回对象的说明。

主要属性

属性描述
code数字,例如 400
message信息,例如 "请求参数没填好"
response自定义的 schema 的实体类

例子

@RequestMapping(value = "/ceshia", method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "post请求测试",notes = "测试2",position = 2)
@ApiResponses({
    @ApiResponse(code = 200,message = "success",response = RequestCode200.class),
    @ApiResponse(code = 509,message = "服务器校验错误",response = RequestCode509.class),
    @ApiResponse(code = 410,message = "参数错误",response = RequestCode410.class),
    @ApiResponse(code = 510,message = "系统错误",response = RequestCode510.class)
})
public String ceshia(@RequestBody String str){
    JSONObject json = new JSONObject();
    json.put("requestType","postType");
    json.put("body",str);

    return json.toString();
}

效果:

img

6、@ApiModel、@ApiModelProperty

描述:

  • @ApiModel 用于描述一个 Model 的信息(这种一般用在 post 创建的时候,使用 @RequestBody 这样的场景,请求参数无法使用 @ApiImplicitParam 注解进行描述的时候)。
  • @ApiModelProperty 用来描述一个 Model 的属性。

主要属性

例子

package com.github.swaggerplugin.codes;

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


@ApiModel("RequestCode200")
public class RequestCode200 {


    @ApiModelProperty(value = "响应码",name = "messageCode",example = "200")
    private Integer messageCode;

    @ApiModelProperty(value = "返回消息",name = "message",example = "success")
    private String message;


    public Integer getMessageCode() {
        return messageCode;
    }

    public void setMessageCode(Integer messageCode) {
        this.messageCode = messageCode;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}

效果:

img

7、@PathVariable

描述:

@PathVariable 用于获取 get 请求 url 路径上的参数,即参数绑定的作用,通俗的说是 url 中 "?" 前面绑定的参数。

例如:www.baidu.com/name=zhengh…

例子

@GetMapping("/get")
@ResponseBody
@ApiOperation(value = "get请求测试",notes = "get请求",position = 1)
public String get(@ApiParam(required = true,value = "name",example = "张三",name = "name") @PathVariable("name") String name){
    JSONObject json = new JSONObject();
    json.put("requestType","getType");
    json.put("name",name);
    json.put("id","123");

    return json.toString();
}

注:如果不加这个的话,默认就是 body 类型的,body 类型也就是接收的是 json 格式的数据。

8、@RequestParam

描述:

@RequestParam 用于获取前端传过来的参数,可以是 get、post 请求,通俗的说是 url 中 "?" 后面拼接的每个参数。

例子

@GetMapping("/get")
@ResponseBody
@ApiOperation(value = "get请求测试",notes = "get请求",position = 1)
public String get(@ApiParam(required = true,value = "name",example = "张三",name = "name") @RequestParam("name") String name){
    JSONObject json = new JSONObject();
    json.put("requestType","getType");
    json.put("name",name);
    json.put("id","123");

    return json.toString();
}

(一)注解是什么?如何自定义注解?

对于注解的讲解部分,我之前整理过一篇比较详细的文章,此处就不在过多的说明了,可以参考我的下列文章:

WX 公众号:什么是注解?如何定义注解

CSDM:你说啥什么? 注解你还不会?

(二)为什么要扩展 Swagger 功能以及扩展后的效果

答:

当然是 Swagger 当前的功能不能满足我们当前项目的现状了。

其实 Swagger 的已有的功能也能满足我们的需求,但是对代码的侵入性太大了。

一句话了解侵入性:

当你的代码引入了一个组件, 导致其它代码或者设计, 要做相应的更改以适应新组件. 这样的情况我们就认为这个新组件具有侵入性

同时, 这里又涉及到一个设计方面的概念, 就是耦合性的问题.

我们代码设计的思路是 " 高内聚, 低耦合 ", 为了实现这个思路, 就必须降低代码的侵入性.

摘自:一句话让你明白代码的侵入性

Swagger 的优点有很多,有优点,必定有缺点,这是谁也改变不了的,我们能做到的就是减少缺点。

优点前面已经说了,我总结如下,当然了还有其他的:

  • 1、可以跟据业务代码自动生成相关的 api 接口文档,尤其用于 restful 风格中的项目;
  • 2、开发人员几乎可以不用专门去维护 rest api,这个框架可以自动为你的业务代码生成 restfut 风格的 api;
  • 3、而且还提供相应的测试界面,自动显示 json 格式的响应。
  • 4、大大方便了后台开发人员与前端的沟通与联调成本。

对于缺点:

  • 1、不方便维护(当接口变动了,每次都需要去修改相应的参数配置);
  • 2、关于 Swagger 的代码太多,严重的覆盖了原有的 java 逻辑代码(重点);
  • 3、当一个接口有多个响应实例是,不能显示多个,只能显示一个(例如自定义的响应参数:401 的响应码就包括:密码错误,参数错误,id 错误等);
  • 4、当接口接收的参数为 json 字符串的时候,在 Swagger 的 UI 中不能显示 JSON 字符串中具体的参数(与前端交接会出现问题,前端会不知道他要传递给你什么);

本文要解决的问题也是对于缺点的弥补,通过扩展 Swagger 的功能来解决这些问题。

反例:

天哪,这只是一个接口,就占了 80 多行。

@ResponseBody
@RequestMapping(method = RequestMethod.GET)
@ApiOperation(position = 2,value = "9.2.获取人工监管配置",notes = "<p><strong>请求的url:</strong></p>\n" +
              "<p>/api/background/config/robotMonitorConfig</p>\n" +
              "<p><strong>返回的成功数据:</strong></p>\n" +
              "<details> \n" +
              "<summary>点击展开查看</summary> \n" +
              "<pre><code class=\"language-json\">{\n" +
              "\n" +
              "    message: "success",\n" +
              "\n" +
              "    messageCode:"200",\n" +
              "\n" +
              "    result: [\n" +
              "\n" +
              "        {\n" +
              "\n" +
              "            id: 1,\n" +
              "\n" +
              "            robotId: 18,\n" +
              "\n" +
              "            authStatus: 1,\n" +
              "\n" +
              "            warnStatus: 1,\n" +
              "\n" +
              "            warnRule: \n" +
              "\n" +
              "            {\n" +
              "\n" +
              "                "angry":1,\n" +
              "\n" +
              "                "unknown":1,\n" +
              "\n" +
              "                "down":1,\n" +
              "\n" +
              "                "sameAnswer":1,\n" +
              "\n" +
              "                "noClick":1,\n" +
              "\n" +
              "                "keywords":1\n" +
              "\n" +
              "            },\n" +
              "\n" +
              "            warnKeywords: \n" +
              "\n" +
              "            [\n" +
              "\n" +
              "                "转人工",\n" +
              "\n" +
              "                "人工回复"\n" +
              "\n" +
              "            ],\n" +
              "\n" +
              "            operatorId: "qubb",\n" +
              "\n" +
              "            lastModifyTime: 231431341343123\n" +
              "\n" +
              "        }\n" +
              "\n" +
              "    ]\n" +
              "\n" +
              "}\n" +
              "\n" +
              "</code></pre>\n" +
              "</details>\n" +
              "<p><strong>返回的失败数据:</strong></p>\n" +
              "<details> \n" +
              "<summary>点击展开查看</summary> \n" +
              "<pre><code class=\"language-json\">{\n" +
              "    message: "当前用户已退出登陆,请登陆后重试",\n" +
              "    messageCode:"509"\n" +
              "}\n" +
              "\n" +
              "{\n" +
              "    message: "param robotId error",\n" +
              "    messageCode:"410"\n" +
              "}\n" +
              "\n" +
              "{\n" +
              "    message: "system error",\n" +
              "    messageCode:"510"\n" +
              "}\n" +
              "\n" +
              "</code></pre>\n" +
              "</details>\n" +
              "\n" +
              "\n" +
              "\n")
public Object xxx(@ApiParam(value = "机器人ID",defaultValue = "7",required = true) @RequestParam(value = "robotId", required = false) String robotIdStr) {

}

经过我对功能的扩展:

一行代码轻松搞定

@APiFileInfo("/xxx")

(三)前奏准备

1、必须要了解的 Spring 的三个注解

  • (1)@Component(把普通 pojo 实例化到 spring 容器中,相当于配置文件中的)
  • (2)@Order(1) (调整这个类被注入的顺序,也可以说是优先级)
  • (3)@Configuration (用于定义配置类,可替换 xml 配置文件,被注解的类内部包含有一个或多个被 @Bean 注解的方法,这些方法将会被 AnnotationConfigApplicationContext 或 AnnotationConfigWebApplicationContext 类进行扫描,并用于构建 bean 定义,初始化 Spring 容器。)

2、Swagger 的可扩展组件

在源码中:可以看到下图所示的一些 Plugin 结尾的接口文件,我们就是要在这些上面做文章的。

关于具体的介绍,可以去本文最后,去查看另一篇文章,对于这些接口的详细分析,本文不再说明。

img

(一)实战一:针对传递 json 字符串的参数,使其具有相关参数的描述的功能

1、需求来源

有需求,就有需求来源或者说是需求的产生。首先要知道为什么会有这个需求呢?我们先来看为什么会有这个需求。

我们拿三个接口做示范吧:

@Controller("/studentController")
@Api(tags = "学生Controller",position = 1)
public class StudentController {

    
    @GetMapping("/getStudentById")
    @ApiOperation(value = "根据学生ID获取学生信息",notes = "根据传入的学生ID获取学生信息",position = 1)
    public Object getStudentById(String id){
        return "id="+id;
    }

    
    @PostMapping("/addStudent")
    @ApiOperation(value = "添加学生信息",notes = "添加学生信息",position = 1)
    public Object addStudent(@RequestBody Student student){
        return "student="+student.toString();
    }


    
    @PostMapping("/addStudent2")
    @ApiOperation(value = "含有特殊字段的,添加学生信息",notes = "含有特殊字段的,添加学生信息",position = 1)
    public Object addStudentStr(@RequestBody String str){
        return "str="+str;
    }

}

分析 1:

getStudentById(String id) 接口只传递一个 id。

页面效果如下:

img

测试功能页面如下:

img

分析 2:

addStudent(@RequestBody Student student) 接口需要传递一个 json 数据类型的对象。

页面效果如下:

img

测试功能页面如下:

img

分析 3:(问题就出在这了,注意看哦

addStudentStr(@RequestBody String str) 接口需要传递一个 json 数据类型字符串。

页面效果如下:

img

测试功能页面如下:

img

2、需求分析

通过分析1分析2分析3,三个实例可知,当传递参数为json字符串的时候,是不会显示具体的参数的。这就造成了前端人员根本就无法知道传递的是什么

我们的需求,简单,明了,直接。就是针对传递的参数为json字符串格式的参数时实现有相关参数的描述的功能

3、开发思路

(1)走的弯路

你首先可能想到的是:在自定义一个类呗,里面写上你需求的字段,这样不就有了吗。

首先这种办法是可以的;

但是存在的问题也是相当大的,如果我只有几个接口的话,还可以。但是一个项目有几百个接口就需要定义几百个类。经过团队讨论,这种方法被 kill 了。

img

(2)正确的路

可以自定义一个注解,把注解加在需要加的参数上。然后通过注解的传值,去自动生成类。

这种方法是可行的。

有很多可以动态创建类的方法,经过我亲自实践,选择了:Javassist的ClassPool机制

如果对 ClassPool 有兴趣的话,可以自行查阅资料去了解下,此处就不在过多赘述了。

4、关键代码

关于自定义的注解,描述的很详细,就不多说了。

@Apicp注解的定义

package com.github.swaggerplugin.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Target({ElementType.PARAMETER, ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Apicp {
    Class<?> classPath();
    String modelName();
    String values()[]; 
    String noValues()[] default {} ;
    String noValueTypes()[] default {};
    String noVlaueExplains()[] default {};
}

@ApiIgp注解的定义

package com.github.swaggerplugin.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Target({ElementType.PARAMETER, ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ApiIgp {
    Class<?> classPath();
    String modelName();
    String values()[]; 
    String noValues()[] default {} ;
    String noValueTypes()[] default {};
    String noVlaueExplains()[] default {};
}

自定义完了注解,但是怎么让他起作用呢?这是一步最关键的地方。

在 Spring 中的自动装配原理,可以去了解下。在本项目中,我们使用的是 Spring 的@Component注解或者@Configuration注解来实现的自动注入到 pojo 中。前面已经介绍了这俩注解的作用。

通过翻阅SpringFox(Swagger)knife4j-spring-boot的源代码,我发现如果自定义扩展功能的话,只需要实现某个xxxPlugin的接口中的apply方法就可以。apply方法中我们去手动扫描我们自定义的注解,然后加上相关实现的逻辑即可。

代码是没放全的,太长了,只选择了部分来放。感兴趣的话,可以去我的 github 上拉取,随后我还会说如何直接应用的办法。

@Configuration
@Order(-19999)   
public class SwaggerModelReader implements ParameterBuilderPlugin {

    @Autowired
    private TypeResolver typeResolver;

    static final Map<String,String> MAPS = new HashMap<>();
    static {
        MAPS.put("byte","java.lang.Byte");
        MAPS.put("short","java.lang.Short");
        MAPS.put("integer","java.lang.Integer");
        MAPS.put("long","java.lang.Long");
        MAPS.put("float","java.lang.Float");
        MAPS.put("double","java.lang.Double");
        MAPS.put("char","java.lang.Character");
        MAPS.put("string","java.lang.String");
        MAPS.put("boolean","java.lang.Boolean");
    }

    
    static public String getTypePath(String key){
        return key==null || !MAPS.containsKey(key.toLowerCase()) ? null :  MAPS.get(key.toLowerCase());
    }


    @Override
    public void apply(ParameterContext context) {
        ResolvedMethodParameter methodParameter = context.resolvedMethodParameter();

        
        Optional<ApiIgp> apiIgp = methodParameter.findAnnotation(ApiIgp.class);
        Optional<Apicp> apicp = methodParameter.findAnnotation(Apicp.class);



        if (apiIgp.isPresent() || apicp.isPresent()) {
            Class originClass = null;
            String[] properties = null; 
            Integer annoType = 0;
            String name = null + "Model" + 1;  

            String[] noValues = null;
            String[] noValueTypes = null;
            String[] noVlaueExplains = null;
            
            if (apiIgp.isPresent()){
                properties = apiIgp.get().values(); 
                originClass = apiIgp.get().classPath();
                name = apiIgp.get().modelName() ;  

                noValues = apiIgp.get().noValues();
                noValueTypes = apiIgp.get().noValueTypes();
                noVlaueExplains = apiIgp.get().noVlaueExplains();

            }else {
                properties = apicp.get().values(); 
                annoType = 1;
                originClass = apicp.get().classPath();
                name = apicp.get().modelName() ;
                noValues = apicp.get().noValues();
                noValueTypes = apicp.get().noValueTypes();
                noVlaueExplains = apicp.get().noVlaueExplains();
            }

            
            Class newClass = createRefModelIgp(properties, noValues, noValueTypes, noVlaueExplains, name, originClass, annoType);


            context.getDocumentationContext()
                    .getAdditionalModels()
                    .add(typeResolver.resolve(newClass));  


            context.parameterBuilder()  
                    .parameterType("body")
                    .modelRef(new ModelRef(name))
                    .name(name);

        }


    }

    
    private Class createRefModelIgp(String[] properties, String[] noValues, String[] noValueTypes, String[] noVlaueExplains, String name, Class origin, Integer annoType) {
        try {
            
            Field[] fields = origin.getDeclaredFields();
            
            List<Field> fieldList = Arrays.asList(fields);
            
            List<String> dealProperties = Arrays.asList(properties);
            
            List<Field> dealFileds = fieldList
                    .stream()
                    .filter(s ->
                            annoType==0 ? (!(dealProperties.contains(s.getName()))) 
                                        : dealProperties.contains(s.getName())
                            ).collect(Collectors.toList());

            
            List<String> noDealFileds = Arrays.asList(noValues);
            List<String> noDealFiledTypes = Arrays.asList(noValueTypes);
            List<String> noDealFiledExplains = Arrays.asList(noVlaueExplains);


            
            ClassPool pool = ClassPool.getDefault();
            CtClass ctClass = pool.makeClass(origin.getPackage().getName()+"."+name);

            
            createCtFileds(dealFileds,noDealFileds,noDealFiledTypes,noDealFiledExplains,ctClass,annoType);

            
            return ctClass.toClass();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    @Override
    public boolean supports(DocumentationType delimiter) {
        return true;
    }

    
    public void createCtFileds(List<Field> dealFileds, List<String> noDealFileds, List<String> noDealFiledTypes,List<String> noDealFiledExplains, CtClass ctClass, Integer annoType) {
       

        for (Field field : dealFileds) {
            CtField ctField = null;
            try {
                ctField = new CtField(ClassPool.getDefault().get(field.getType().getName()), field.getName(), ctClass);
            } catch (CannotCompileException e) {
                System.out.println("找不到了1:"+e.getMessage());
            } catch (NotFoundException e) {
                System.out.println("找不到了2:"+e.getMessage());
            }
            ctField.setModifiers(Modifier.PUBLIC);
            ApiModelProperty annotation = field.getAnnotation(ApiModelProperty.class);
            String apiModelPropertyValue = java.util.Optional.ofNullable(annotation).map(s -> s.value()).orElse("");



            if (StringUtils.isNotBlank(apiModelPropertyValue)) { 
                ConstPool constPool = ctClass.getClassFile().getConstPool();

                AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
                Annotation ann = new Annotation(ApiModelProperty.class.getName(), constPool);
                ann.addMemberValue("value", new StringMemberValue(apiModelPropertyValue,constPool));
                attr.addAnnotation(ann);

                ctField.getFieldInfo().addAttribute(attr);
            }
            try {
                ctClass.addField(ctField);
            } catch (CannotCompileException e) {
                System.out.println("无法添加字段1:"+e.getMessage());
            }
        }

        
         for (int i = 0; i < noDealFileds.size(); i++) {
            String valueName = noDealFileds.get(i);
            String valueType = noDealFiledTypes.get(i);
            valueType=getTypePath(valueType);

            
             CtField ctField = null;
             try {
                 ctField = new CtField(ClassPool.getDefault().get(valueType), valueName, ctClass);
             } catch (CannotCompileException e) {
                 System.out.println("找不到了3:"+e.getMessage());
             } catch (NotFoundException e) {
                 System.out.println("找不到了4:"+e.getMessage());
             }
             ctField.setModifiers(Modifier.PUBLIC);

             if(noDealFiledExplains.size()!=0){
                 
                 String apiModelPropertyValue = (apiModelPropertyValue=noDealFiledExplains.get(i))==null?"无描述":apiModelPropertyValue;

                 System.out.println(apiModelPropertyValue);

                 if (StringUtils.isNotBlank(apiModelPropertyValue)) { 
                     ConstPool constPool = ctClass.getClassFile().getConstPool();
                     AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
                     Annotation ann = new Annotation(ApiModelProperty.class.getName(), constPool);
                     ann.addMemberValue("value", new StringMemberValue(apiModelPropertyValue,constPool));
                     attr.addAnnotation(ann);

                     ctField.getFieldInfo().addAttribute(attr);
                 }

             }

             
             try {
                 ctClass.addField(ctField);
             } catch (CannotCompileException e) {
                 System.out.println("无法添加字段2:"+e.getMessage());
             }

         }

    }
}

5、实战成果

我们修改接口如下:

@PostMapping("/addStudent2")
@ApiOperation(value = "含有特殊字段的,添加学生信息",notes = "含有特殊字段的,添加学生信息",position = 1)
public Object addStudentStr(@Apicp(values = {"Id","name"}, 
                                   modelName = "addStudent2", 
                                   classPath = Student.class, 
                                   noValues = {"lala","haha","xixi"}, 
                                   noValueTypes = {"string","integer","double"},
                                   noVlaueExplains = {"啦啦","哈哈","嘻嘻"})
                            @RequestBody String str){
    return "str="+str;
}

效果:

可以看到,我们自定义的注解起作用了,而且参数名称,参数说明,数据类型都有了。

注:是否必须这个选项,下次升级,就会有了。

img

在调试的时候,也可以看到,也有了:

img

这样就不用我们再去手动为几百个接口创建几百个类了。

(二)实战二:减少在 Controller 中 Swagger 的代码,使其可以从某些文件中读取信息,自动配置 Swagge 的功能

1、需求来源

我们需要对接口的返回值进行描述,例如:

code 为 200 的返回值:(来源:我从简书上的 api 返回的结果拷贝过来的)

[    {        "id":62564697,        "slug":"09c7db472fa6",        "title":"Java的SPI机制",        "view_count":42,        "user":{            "id":12724216,            "nickname":"bdqfork",            "slug":"a2329f464833",            "avatar":"https://upload.jianshu.io/users/upload_avatars/12724216/6f2b07cc-e9bf-440d-a6ad-49fbaa3b49ce.jpg"        }    },    {        "id":62564140,        "slug":"ec3bd614dcb0",        "title":"SLF4J日志级别以及使用场景",        "view_count":381,        "user":{            "id":12724216,            "nickname":"bdqfork",            "slug":"a2329f464833",            "avatar":"https://upload.jianshu.io/users/upload_avatars/12724216/6f2b07cc-e9bf-440d-a6ad-49fbaa3b49ce.jpg"        }    }]

code 为 410 的返回值:

{
    "messageCode": 410,
    "message": "姓名不能为空"
}

code 为 509 的返回值:

{
    "messageCode": 509,
    "message": "姓名长度不超过15"
}

{
    "messageCode": 509,
    "message": "姓名数量不能超过15个"
}

{
    "messageCode": 509,
    "message": "姓名已存在"
}

{
    "messageCode": 509,
    "message": "存在姓名,暂不可新增"
}

code 为 510 的返回值:

{
    "messageCode": 510,
    "message": "system error"
}

我们可以这样加:

    @GetMapping("/getStudentById")
    @ApiOperation(value = "根据学生ID获取学生信息",notes = "" +
            "[\n" +
            "    {\n" +
            "        \"id\":62564697,\n" +
            "        \"slug\":\"09c7db472fa6\",\n" +
            "        \"title\":\"Java的SPI机制\",\n" +
            "        \"view_count\":42,\n" +
            "        \"user\":{\n" +
            "            \"id\":12724216,\n" +
            "            \"nickname\":\"bdqfork\",\n" +
            "            \"slug\":\"a2329f464833\",\n" +
            "            \"avatar\":\"https://upload.jianshu.io/users/upload_avatars/12724216/6f2b07cc-e9bf-440d-a6ad-49fbaa3b49ce.jpg\"\n" +
            "        }\n" +
            "    },\n" +
            "    {\n" +
            "        \"id\":62564140,\n" +
            "        \"slug\":\"ec3bd614dcb0\",\n" +
            "        \"title\":\"SLF4J日志级别以及使用场景\",\n" +
            "        \"view_count\":381,\n" +
            "        \"user\":{\n" +
            "            \"id\":12724216,\n" +
            "            \"nickname\":\"bdqfork\",\n" +
            "            \"slug\":\"a2329f464833\",\n" +
            "            \"avatar\":\"https://upload.jianshu.io/users/upload_avatars/12724216/6f2b07cc-e9bf-440d-a6ad-49fbaa3b49ce.jpg\"\n" +
            "        }\n" +
            "    }\n" +
            "]",position = 1)
    
    public Object getStudentById(String id){
        return "id="+id;
    }

页面效果:

img

我们要做的就是来纠正这个。

而且这一个 200 的接口描述就占了一个屏幕:

img

当一个 controller 有好多个接口该如何是好的,一定会被接口的描述所覆盖的。这就是我们需求的来源。

2、需求分析

看到页面效果

你可能会有疑惑为什么加了 \ n 也不能回车显示,我去查阅了 Swagger 的 UI 源码是如何展现出来的。原理是通过 makdown 的方式,通过渲染得到的。所以我们可以把 makdown 的语法转换成 html 语法进行实现,经过我编写的转换小工具之后,发现是可以的。

3、开发思路

先去网上查查是否有相应的转换工具。

我们先引入一下,就是通过这个来做转换的:

<dependency>
    <groupId>com.vladsch.flexmark</groupId>
    <artifactId>flexmark-all</artifactId>
    <version>0.50.42</version>
</dependency>

实现的代码很简单:

MutableDataSet options = new MutableDataSet();
Parser parser = Parser.builder(options).build();
HtmlRenderer renderer = HtmlRenderer.builder(options).build();


Node document = parser.parse(mdBody.toString());


String html = renderer.render(document);  

运行之后就会得到转换后的 html 语法:

img

我们把转换后的 html 代码复制到接口描述中:

@GetMapping("/getStudentById")
@ApiOperation(value = "根据学生ID获取学生信息",notes = "" +
              "<pre><code class=\"language-json\">[\n" +
              "    {\n" +
              "        "id":62564697,\n" +
              "        "slug":"09c7db472fa6",\n" +
              "        "title":"Java的SPI机制",\n" +
              "        "view_count":42,\n" +
              "        "user":{\n" +
              "            "id":12724216,\n" +
              "            "nickname":"bdqfork",\n" +
              "            "slug":"a2329f464833",\n" +
              "            "avatar":"https://upload.jianshu.io/users/upload_avatars/12724216/6f2b07cc-e9bf-440d-a6ad-49fbaa3b49ce.jpg"\n" +
              "        }\n" +
              "    },\n" +
              "    {\n" +
              "        "id":62564140,\n" +
              "        "slug":"ec3bd614dcb0",\n" +
              "        "title":"SLF4J日志级别以及使用场景",\n" +
              "        "view_count":381,\n" +
              "        "user":{\n" +
              "            "id":12724216,\n" +
              "            "nickname":"bdqfork",\n" +
              "            "slug":"a2329f464833",\n" +
              "            "avatar":"https://upload.jianshu.io/users/upload_avatars/12724216/6f2b07cc-e9bf-440d-a6ad-49fbaa3b49ce.jpg"\n" +
              "        }\n" +
              "    }\n" +
              "]\n" +
              "</code></pre>\n" +
              "\n" +
              "\n" +
              "",position = 1)
public Object getStudentById(String id){
    return "id="+id;
}

再次看一下效果:

img

果然是可以的。

但是如果有几百个接口的话,你还去一个一个去复制粘贴吗?

下面就是来解决当有大量接口的时候如何办的问题。

4、关键代码

关于 makdown 转换成 html 语法的代码如下:

我是做了升级的,当遇到代码块的时候会变成折叠的。

public class MdToHtml {
    
    public final static String makdownToHtml(String md) {
        StringBuilder mdBody = new StringBuilder();

        
        for (int i = 0; i < md.length() ; i++) {
            
            StringBuilder newCodeBody = new StringBuilder();
            newCodeBody.append("\n\n");
            newCodeBody.append("<details> \n");
            newCodeBody.append("\n");
            newCodeBody.append("<summary>点击展开查看</summary> \n");

            
            if(md.charAt(i)=='`' && md.charAt(i+1)=='`' && md.charAt(i+2)=='`'){

                String temp = md.substring(i+3);
                int strIndex = findStrIndex(temp);

                String codeType = md.substring(i + 3, i + 3 + strIndex);

                newCodeBody.append("\n```"+codeType+"\n");

                
                for (int j = i+3+strIndex+1; j < md.length() ; j++) {
                    
                    if(md.charAt(j)=='`' && md.charAt(j+1)=='`' && md.charAt(j+2)=='`'){
                        i=j+3; 

                        
                        newCodeBody.append("\n```\n");

                        
                        newCodeBody.append("\n");
                        newCodeBody.append("</details>");
                        newCodeBody.append("\n");

                        break;
                    }else{
                        
                        newCodeBody.append(md.charAt(j));
                    }
                }

                
                mdBody.append(newCodeBody.toString());

            }else{
                
                mdBody.append(md.charAt(i));
            }
        }

        
        MutableDataSet options = new MutableDataSet();
        Parser parser = Parser.builder(options).build();
        HtmlRenderer renderer = HtmlRenderer.builder(options).build();

        
        Node document = parser.parse(mdBody.toString());

        
        String html = renderer.render(document);  

        return html;
    }

    static private int findStrIndex(String str){
        int sum = 0;
        for (int i = 0; i <str.length() ; i++) {
            if(str.charAt(i)=='\n')
                return sum++;
            else
                sum++;
        }
        return -1;
    }
    
}

如果用了,效果会是这样:

img

可以展开,可以合上。

纯粹是利用了 makdown 的语法来实现的。

img

依然首先自定义一个注解:

package com.github.swaggerplugin.annotation;


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.PARAMETER, ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface APiFileInfo {

    String value() default "";
}

该注解的实现:

实现是非常简单的`,`难的是如何解析。
@Component
@Order(1)
public class OperationPositionBulderPlugin implements OperationBuilderPlugin {
    @Autowired
    private TypeResolver typeResolver;

    static Map<String,Map<Integer, APiFileInfoBean>> apiFileInfoMaps = null;


    public static String swaggerMdPaths  = "src/main/resources/md";

    private static boolean flag = false;

    @Value("${swagger.md.paths}")
    private void setSwaggerMdPaths(String swaggerMdPaths){
        OperationPositionBulderPlugin.swaggerMdPaths = swaggerMdPaths;
    }

    
    public OperationPositionBulderPlugin() {
        String[] paths = swaggerMdPaths.split(",");

        System.out.println("开始解析文件了------------>>>>");
        System.out.println("文件地址:"+Arrays.toString(paths));

        if(apiFileInfoMaps==null) {
            apiFileInfoMaps = ReadFromFile.initFileOrDirectory(paths);
            flag=apiFileInfoMaps==null?false:true;
        }
    }

    @Override
    public void apply(OperationContext context) {

        if(flag){
            System.out.println("有文件,加载:"+flag);

        





            
            Optional<APiFileInfo> apiFileInfoOptional = context.findAnnotation(APiFileInfo.class);

            if (apiFileInfoOptional.isPresent()) {

                String flag = null;

                System.out.println("apiFileInfoOptional--->"+apiFileInfoOptional.get().value());
                flag = apiFileInfoOptional.get().value();

                
                context.operationBuilder()
                        .responseMessages(buildResponseMessage(flag, apiFileInfoMaps));
            }




        }else {
            System.out.println("没有文件,不加载");
        }
    }

    
    private Set<ResponseMessage> buildResponseMessage(String flag, Map<String, Map<Integer,APiFileInfoBean>> apiFileInfoMaps) {

        Map<Integer,APiFileInfoBean> aPiFileInfoBean = apiFileInfoMaps.get(flag);
        Set<ResponseMessage> set = new HashSet<>();
        ResponseMessage responseMessage = null;
        if(aPiFileInfoBean!=null)
        for (Integer code : aPiFileInfoBean.keySet()) {

            APiFileInfoBean fileInfoBean = aPiFileInfoBean.get(code);
            responseMessage = new ResponseMessageBuilder()
                                    .code(code)
                                    .message(MdToHtml.makdownToHtml(fileInfoBean.getMessage()))
                                    .responseModel(new ModelRef("UpdateRobotModel"))
                                    .build();

            set.add(responseMessage);
        }

        return set;
    }


    @Override
    public boolean supports(DocumentationType delimiter) {
        return true;
    }
}

解析文件内容:

代码中有很多遗留的 debug 的打印语句,可以忽略。

package com.github.swaggerplugin.util;



import com.github.swaggerplugin.bean.APiFileInfoBean;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class ReadFromFile {

    
    public static Map<String, Map<Integer, APiFileInfoBean>> initFileOrDirectory(String[] mdFileURIs) {

        Map<String, Map<Integer,APiFileInfoBean>> map = new HashMap<>();

        for (String fileURIs : mdFileURIs) {
            File file = new File(fileURIs);

            
            if(file!=null && !file.isFile()){
                
                initDirectory(map,file);
                
            }else if(file!=null && file.isFile()){
                
                initFile(map,file);
            }
        }

        return map.size()<=0?null:map;
    }

    
    private static void initFile(Map<String, Map<Integer,APiFileInfoBean>> map, File file) {
        List<String> list = ReadFileDataToList(file);

        int start = 0;
        int end = 0;

        
        for (int i = 0; i < list.size(); i++) {
            String dataLine = list.get(i);



            
            if(dataLine.startsWith("# URL:")){
                start = i;



                
                for (int j = i+1;j<list.size();j++){
                    String dataLine_start = list.get(j);
                    if(dataLine_start.startsWith("# URL:")) {
                        System.out.println("当前API的起始位置:"+i+"-->"+(j-1));
                        end = j-1;
                        i=j-1;
                        break;
                    }
                }

                
                disposeInterval(start,end,list,map);



            }

        }

        

        System.out.println("当前API的起始位置:"+start+"-->"+(list.size()));
        
        disposeInterval(start,list.size(),list,map);

    }

    
    private static void disposeInterval(int start, int end, List<String> list, Map<String,Map<Integer,APiFileInfoBean>> map) {

        int code_start = 0;
        int code_end = 0;
        String flag = null;

        for (int index = start; index < end ; index++) {
            String s = list.get(index);

            if(s.startsWith("# URL:")){
                flag = s.substring(6, s.length()).replace(" ","");
            }

            
            if(s.replace(" ","").endsWith("---") && s.replace(" ","").equals("---")){
                
                code_start = index+1+1;

                for (int i = index+1; i < end; i++) {
                    s=list.get(i);
                    
                    if(s.replace(" ","").endsWith("---") && s.replace(" ","").equals("---")) {
                        
                        code_end = i-1;
                        
                        index = i-1;
                        System.out.println("code起始位置:"+code_start+"--->"+code_end);
                        
                        disposeCodeInterval(flag,code_start,code_end,list,map);

                        break;
                    }
                }
            }
        }
    }

    
    private static void disposeCodeInterval(String flag, int code_start, int code_end, List<String> list, Map<String, Map<Integer, APiFileInfoBean>> map) {
        APiFileInfoBean aPiFileInfoBean = new APiFileInfoBean();

        Map<Integer,APiFileInfoBean> fileInfoBeanMap = new HashMap<>();

        StringBuilder sb = new StringBuilder();


        for (int index = code_start; index <= code_end ; index++) {
            String s = list.get(index);
            if(s.startsWith("code:")){
                String code = s.substring(5, s.length());

                try {
                    aPiFileInfoBean.setCode(Integer.valueOf(code.replace(" ","")));
                }catch (Exception e){
                    e.fillInStackTrace();
                }

            }else if(s!=null && !(s.replace(" ","")).equals("") ){



                
                if(s.charAt(0)=='`' && s.charAt(1)=='`' && s.charAt(2)=='`'){



                    sb.append(s+"\n");

                    for (int i = index+1; i < list.size() ; i++) {
                        s = list.get(i);

                        sb.append(list.get(i)+"\n");
                        if(s!=null && !(s.replace(" ","").equals("")) &&s.charAt(0)=='`' && s.charAt(1)=='`' && s.charAt(2)=='`'){
                            index=i;
                            break;
                        }
                    }


                }else{

                    sb.append(s+"\n");
                }
            }else{


                sb.append(list.get(index)+"\n");
            }
        }



        aPiFileInfoBean.setMessage(sb.toString());





        if(flag!=null && !flag.equals("") && aPiFileInfoBean!=null){
            fileInfoBeanMap.put(aPiFileInfoBean.getCode(),aPiFileInfoBean);
            Map<Integer, APiFileInfoBean> fileInfoBeanMap1 = map.get(flag);
            if(fileInfoBeanMap1!=null)
                fileInfoBeanMap.putAll(fileInfoBeanMap1);

            map.put(flag,fileInfoBeanMap);
        }
    }


    
    private static void initDirectory(Map<String, Map<Integer,APiFileInfoBean>> map, File file) {

        

        
        File[] files = file.listFiles();
        for (File fi : files) {
            if(!fi.isFile()){
                System.out.println(fi+"-->是目录");
                initDirectory(map,fi);
            }else{
                System.out.println(fi+"-->是文件");
                initFile(map,fi);
            }
        }
        System.out.println("---");

        

    }





    
    public static List<String> ReadFileDataToList( File file) {
        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        List<String> list = new ArrayList<>();

        try {
            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis);
            br = new BufferedReader(isr);
            String dataLine = null;


            while((dataLine = br.readLine()) != null) {

                list.add(dataLine);

            }

        } catch (FileNotFoundException e) {
            System.out.println("解析文件不存在"+e.getMessage());
        } catch (IOException e) {
            System.out.println("解析文件出错了:"+e.getMessage());
        } finally {
            try {
                if(br != null) br.close();
                if(isr != null) isr.close();
                if(fis != null) fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return list;

    }
}

5、实战成果

我们的成果就是完成了一个注解。

注解:APiFileInfo("flag")

然后该注解就会从相应的文件中按规则进行解析出来。

xxxx.md 文件存放在src/main/resources/md下,内容如下:

# URL:/getStudentById

---

code:200

**这是200响应码的描述**

​```json
 [
    {
        "id":62564697,
        "slug":"09c7db472fa6",
        "title":"Java的SPI机制",
        "view_count":42,
        "user":{
            "id":12724216,
            "nickname":"bdqfork",
            "slug":"a2329f464833",
            "avatar":"https://upload.jianshu.io/users/upload_avatars/12724216/6f2b07cc-e9bf-440d-a6ad-49fbaa3b49ce.jpg"
        }
    },
    {
        "id":62564140,
        "slug":"ec3bd614dcb0",
        "title":"SLF4J日志级别以及使用场景",
        "view_count":381,
        "user":{
            "id":12724216,
            "nickname":"bdqfork",
            "slug":"a2329f464833",
            "avatar":"https://upload.jianshu.io/users/upload_avatars/12724216/6f2b07cc-e9bf-440d-a6ad-49fbaa3b49ce.jpg"
        }
    }
]
​```

---

code:410

### 517状态码的描述
​```json
{
    "messageCode": 410,
    "message": "姓名不能为空"
}
​```

---



code:509

#### 510测试描述
​```json
{
    "messageCode": 509,
    "message": "姓名长度不超过15"
}

{
    "messageCode": 509,
    "message": "姓名数量不能超过15个"
}

{
    "messageCode": 509,
    "message": "姓名已存在"
}

{
    "messageCode": 509,
    "message": "存在姓名,暂不可新增"
}
​```

---

接口代码修改如下:

这样是不是就很方便了,不在有大批量的代码,也不会显得特别的乱了。

@GetMapping("/getStudentById")
@ApiOperation(value = "根据学生ID获取学生信息",notes = "",position = 1)
@APiFileInfo("/getStudentById")
public Object getStudentById(String id){
    return "id="+id;
}

效果如下:

img

是不是很方便了,看着还有多余的状态码,401,403 这些事系统默认的,我们可以关闭:

img

 return new Docket(DocumentationType.SWAGGER_2)
                .useDefaultResponseMessages(false)

再来看就比较简洁了:

img

1、持续关注此 GitHub 仓库:github.com/8042965/swa…

2、拉取该仓库代码;

3、想办法引入到你的项目中;

4、使用步骤很简单和前面第三部分实战环节的一样,通过注解就可以了。

也可以加我的微信进行交流:weiyi3700,QQ 也行:8042965

也可以关注我的微信公众号:TrueDei,回复 swagger-plugin 也可以拿到。

1、自定义注解时,@Order() 注解如何有效的使用?

如何你想调整这个类被注入的顺序,也可以说是优先级。

那么我们可以通过调整 @Order 的值来调整类执行顺序的优先级,即执行的先后。

这就是 @Order 注解的作用。

该注解默认的优先级:

如果不指定,那么就会使用默认的这个优先级级别。

可想而知,如果你有个东西需要先加载的话,如果不指定,或者指定的优先级级别很低,那么很有可能加载不出来。我就遇到了这个问题。

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
@Documented
public @interface Order {
    int value() default 2147483647;
}

再来看一下Ordered这个接口:

public interface Ordered {
    int HIGHEST_PRECEDENCE = -2147483648;
    int LOWEST_PRECEDENCE = 2147483647;

    int getOrder();
}

这个类可把我害惨了,具体怎么参的,请看:

当我自定义一个注解,并想使用 Spring 注入到 bean 中:

我从网上查的是使用 @Order(Ordered.HIGHEST_PRECEDENCE) 这个注解来指定顺序,由于指定好之后并没有去看一下具体是做什么的,就导致有些参数是无法被加载到的。

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)

public class OperationPositionBulderPlugin implements OperationBuilderPlugin {
		.........忽略代码
}

可以看到我已经指定好了 200 的相关数据,但是并没有起到效果。

img

解决办法:切换个高优先级:

@Component

@Order(999999)
public class OperationPositionBulderPlugin implements OperationBuilderPlugin {
		........
}

再来看一下:

img

@Order 实验,来源:

blog.csdn.net/yaomingyang…

@Component
@Order(1)
public class BlackPersion implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("----BlackPersion----");
    }
}

@Component
@Order(0)
public class YellowPersion implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("----YellowPersion----");
    }
}

打印结果:

----YellowPersion----
----BlackPersion----

1、八一菜刀 springfox 源码解读

2、Swagger 常用注解

3、一句话让你明白代码的侵入性

所有的代码均放在:

GitHub 仓库:github.com/8042965/swa…