承接上篇文章 《一站式解决使用枚举的各种痛点》 文章最后提到:在使用 swagger 来编写接口文档时,需要告诉前端枚举类型有哪些取值,每次增加取值之后,不仅要改代码,还要找到对应的取值在哪里使用了,然后修改 swagger 文档。反正小黑我觉得这样做很不爽,那有没有什么办法可以让 swagger 框架来帮我们自动列举出所有的枚举数值呢?

这期小黑同学就来讲讲解决方案。

先来看一下效果,有一个感性的认识

请注意哦,这里是课程类型不是我们手动列举出来的,是swagger框架帮我们自动列举的。对应的代码如下:

那么,这是怎么做到的呢?

简单描述一下实现:

1、自定义 SwaggerDisplayEnum 注解,注解中有两个属性,这两个属性是用来干什么的呢?小黑我先不说,大家往下阅读,相信就能明白啦~

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface SwaggerDisplayEnum {
String index() default "index"; String name() default "name"; }

2、在我们的自定义枚举类中标记 @SwaggerDisplayEnum 注解

@Getter
@AllArgsConstructor
@SwaggerDisplayEnum(index = "type", name = "desc")
public enum CourseType { /**
* 图文
*/
PICTURE(102, "图文"),
/**
* 音频
*/
AUDIO(103, "音频"),
/**
* 视频
*/
VIDEO(104, "视频"),
/**
* 外链
*/
URL(105, "外链"),
; @JsonValue
private final int type;
private final String desc; private static final Map<Integer, CourseType> mappings; static {
Map<Integer, CourseType> temp = new HashMap<>();
for (CourseType courseType : values()) {
temp.put(courseType.type, courseType);
}
mappings = Collections.unmodifiableMap(temp);
} @EnumConvertMethod
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
@Nullable
public static CourseType resolve(int index) {
return mappings.get(index);
} }

3、实现 ModelPropertyBuilderPlugin 接口,扩展 swagger,实现在文档中列举所有的枚举值。

public class EnumModelPropertyBuilderPlugin implements ModelPropertyBuilderPlugin {

    @Override
public void apply(ModelPropertyContext context) {
Optional<BeanPropertyDefinition> optional = context.getBeanPropertyDefinition();
if (!optional.isPresent()) {
return;
} final Class<?> fieldType = optional.get().getField().getRawType(); addDescForEnum(context, fieldType);
} @Override
public boolean supports(DocumentationType delimiter) {
return true;
} private void addDescForEnum(ModelPropertyContext context, Class<?> fieldType) {
if (Enum.class.isAssignableFrom(fieldType)) {
SwaggerDisplayEnum annotation = AnnotationUtils.findAnnotation(fieldType, SwaggerDisplayEnum.class);
if (annotation != null) {
String index = annotation.index();
String name = annotation.name(); Object[] enumConstants = fieldType.getEnumConstants(); List<String> displayValues =
Arrays.stream(enumConstants)
.filter(Objects::nonNull)
.map(item -> {
Class<?> currentClass = item.getClass(); Field indexField = ReflectionUtils.findField(currentClass, index);
ReflectionUtils.makeAccessible(indexField);
Object value = ReflectionUtils.getField(indexField, item); Field descField = ReflectionUtils.findField(currentClass, name);
ReflectionUtils.makeAccessible(descField);
Object desc = ReflectionUtils.getField(descField, item);
return value + ":" + desc; }).collect(Collectors.toList()); ModelPropertyBuilder builder = context.getBuilder();
Field descField = ReflectionUtils.findField(builder.getClass(), "description");
ReflectionUtils.makeAccessible(descField);
String joinText = ReflectionUtils.getField(descField, builder)
+ " (" + String.join("; ", displayValues) + ")"; builder.description(joinText).type(context.getResolver().resolve(Integer.class));
}
} }
}

4、实现 ParameterBuilderPluginOperationBuilderPlugin 接口,列举枚举参数的所有取值。

public class EnumParameterBuilderPlugin implements ParameterBuilderPlugin, OperationBuilderPlugin {

    private static final Joiner joiner = Joiner.on(",");

    @Override
public void apply(ParameterContext context) {
Class<?> type = context.resolvedMethodParameter().getParameterType().getErasedType();
if (Enum.class.isAssignableFrom(type)) {
SwaggerDisplayEnum annotation = AnnotationUtils.findAnnotation(type, SwaggerDisplayEnum.class);
if (annotation != null) { String index = annotation.index();
String name = annotation.name();
Object[] enumConstants = type.getEnumConstants();
List<String> displayValues = Arrays.stream(enumConstants).filter(Objects::nonNull).map(item -> {
Class<?> currentClass = item.getClass(); Field indexField = ReflectionUtils.findField(currentClass, index);
ReflectionUtils.makeAccessible(indexField);
Object value = ReflectionUtils.getField(indexField, item); Field descField = ReflectionUtils.findField(currentClass, name);
ReflectionUtils.makeAccessible(descField);
Object desc = ReflectionUtils.getField(descField, item);
return value.toString(); }).collect(Collectors.toList()); ParameterBuilder parameterBuilder = context.parameterBuilder();
AllowableListValues values = new AllowableListValues(displayValues, "LIST");
parameterBuilder.allowableValues(values);
}
}
} @Override
public boolean supports(DocumentationType delimiter) {
return true;
} @Override
public void apply(OperationContext context) {
Map<String, List<String>> map = new HashMap<>();
List<ResolvedMethodParameter> parameters = context.getParameters();
parameters.forEach(parameter -> {
ResolvedType parameterType = parameter.getParameterType();
Class<?> clazz = parameterType.getErasedType();
if (Enum.class.isAssignableFrom(clazz)) {
SwaggerDisplayEnum annotation = AnnotationUtils.findAnnotation(clazz, SwaggerDisplayEnum.class);
if (annotation != null) {
String index = annotation.index();
String name = annotation.name();
Object[] enumConstants = clazz.getEnumConstants(); List<String> displayValues = Arrays.stream(enumConstants).filter(Objects::nonNull).map(item -> {
Class<?> currentClass = item.getClass(); Field indexField = ReflectionUtils.findField(currentClass, index);
ReflectionUtils.makeAccessible(indexField);
Object value = ReflectionUtils.getField(indexField, item); Field descField = ReflectionUtils.findField(currentClass, name);
ReflectionUtils.makeAccessible(descField);
Object desc = ReflectionUtils.getField(descField, item);
return value + ":" + desc; }).collect(Collectors.toList()); map.put(parameter.defaultName().or(""), displayValues); OperationBuilder operationBuilder = context.operationBuilder();
Field parametersField = ReflectionUtils.findField(operationBuilder.getClass(), "parameters");
ReflectionUtils.makeAccessible(parametersField);
List<Parameter> list = (List<Parameter>) ReflectionUtils.getField(parametersField, operationBuilder); map.forEach((k, v) -> {
for (Parameter currentParameter : list) {
if (StringUtils.equals(currentParameter.getName(), k)) {
Field description = ReflectionUtils.findField(currentParameter.getClass(), "description");
ReflectionUtils.makeAccessible(description);
Object field = ReflectionUtils.getField(description, currentParameter);
ReflectionUtils.setField(description, currentParameter, field + " , " + joiner.join(v));
break;
}
}
});
}
}
});
}
}

这篇文章比较枯燥,小黑我也不知道该怎么去讲述,只是将源码附录了出来。如果有读者看了之后还是不清楚的话,可以给我留言,我会一一解答。感谢你的阅读~~

相关源码已经上传到了 github:https://github.com/shenjianeng/solution-for-enums

真香警告!扩展 swagger支持文档自动列举所有枚举值的更多相关文章

  1. JAVA中自定义扩展Swagger的能力,自动生成参数取值含义说明,提升开发效率

    大家好,又见面了. 在JAVA做前后端分离的项目开发的时候,服务端需要提供接口文档供周边人员做接口的对接指导.越来越多的项目都在尝试使用一些基于代码自动生成接口文档的工具来替代由开发人员手动编写接口文 ...

  2. springboot+swagger接口文档企业实践(上)

    目录 1.引言 2.swagger简介 2.1 swagger 介绍 2.2 springfox.swagger与springboot 3. 使用springboot+swagger构建接口文档 3. ...

  3. .net core的Swagger接口文档使用教程(二):NSwag

    上一篇介绍了Swashbuckle ,地址:.net core的Swagger接口文档使用教程(一):Swashbuckle 讲的东西还挺多,怎奈微软还推荐了一个NSwag,那就继续写吧! 但是和Sw ...

  4. .net core的Swagger接口文档使用教程(一):Swashbuckle

    现在的开发大部分都是前后端分离的模式了,后端提供接口,前端调用接口.后端提供了接口,需要对接口进行测试,之前都是使用浏览器开发者工具,或者写单元测试,再或者直接使用Postman,但是现在这些都已经o ...

  5. 添加swagger api文档到node服务

    swagger,一款api测试工具,详细介绍参考官网:http://swagger.io/ ,这里主要记录下怎么将swagger api应用到我们的node服务中: 1.任意新建node api项目, ...

  6. springboot成神之——swagger文档自动生成工具

    本文讲解如何在spring-boot中使用swagger文档自动生成工具 目录结构 说明 依赖 SwaggerConfig 开启api界面 JSR 303注释信息 Swagger核心注释 User T ...

  7. springboot+swagger接口文档企业实践(下)

    目录 1.引言 2. swagger接口过滤 2.1 按包过滤(package) 2.2 按类注解过滤 2.3 按方法注解过滤 2.4 按分组过滤 2.4.1 定义注解ApiVersion 2.4.2 ...

  8. Swagger API文档

    Swagger API文档集中化注册管理   接口文档是前后端开发对接时很重要的一个组件.手动编写接口文档既费时,又存在文档不能随代码及时更新的问题,因此产生了像swagger这样的自动生成接口文档的 ...

  9. [BI项目记]-配置Sharepoint2013支持文档版本管理笔记

    做开发或者做方案,写文档是很重要的一个工作,我们经常需要知道文档被修改的次数,谁在什么时间修改的文档,以及在某一个版本中,都修改了哪些内容,以及不同版本的文档之间有什么差别. 如何对文档进行版本管理, ...

随机推荐

  1. Python - 生成随机验证码的3种实现方式

    生成6位随机验证码的3种实现方式如下: 1. 简单粗暴型:所有数字和字母都放入字符串: 2. 利用ascii编码的规律,遍历获取字符串和数字的字符串格式: 3. 引用string库. 方法1代码: i ...

  2. 易学又实用的新特性:for...of

    今天带来的知识点既简单又使用,是不是感觉非常的棒啊,OK,不多说了,咱们开始往下看. for...of 是什么 for...of 一种用于遍历数据结构的方法.它可遍历的对象包括数组,对象,字符串,se ...

  3. 2019-2020-1 20199308《Linux内核原理与分析》第八周作业

    <Linux内核分析> 第七章 可执行程序工作原理 7.1 知识点 1.目标文件:编译器生成的文件,"目标"指平台,它决定了编译器使用的机器指令集. 2.目标文件格式: ...

  4. 同步类的基础AbstractQueuedSynchronizer(AQS)

    同步类的基础AbstractQueuedSynchronizer(AQS) 我们之前介绍了很多同步类,比如ReentrantLock,Semaphore, CountDownLatch, Reentr ...

  5. js 函数的防抖(debounce)与节流(throttle) 带 插件完整解析版 [helpers.js]

    前言:         本人纯小白一个,有很多地方理解的没有各位大牛那么透彻,如有错误,请各位大牛指出斧正!小弟感激不尽.         函数防抖与节流是做什么的?下面进行通俗的讲解. 本文借鉴:h ...

  6. js中的this指针的用法

    首先看下面代码: function funcA() { this.name = "hello"; console.log(this.name); this.show = funct ...

  7. JS基础入门篇(十)— 数组方法

    1.join 作用: 将数组通过指定字符拼接成字符串.语法: string arr.join([separator = ',']);参数: separator可选,如果省略的话,默认为一个逗号.如果 ...

  8. 4.shell基本操作简介

    判断一个命令是不是内置命令,可以用type命令 1.printf :冒号 #:〉 test.txt 这里会建立一个空文件test.txt set -o|grep  emacs 查看 emacs 模式是 ...

  9. CF906D Power Tower

    扩展欧拉定理 CF906D Power Tower 洛谷交的第二个黑题 题意 给出一个序列\(w-1,w_2,\cdots,w_n\),以及\(q\)个询问 每个询问给出\(l,r\),求: \[w_ ...

  10. python(open 文件)

    一.open 文件 1.open('file','mode')打开一个文件 file 要打开的文件名,需加路径(除非是在当前目录) mode 文件打开的模式 需要手动关闭 close 2.with o ...