真香警告!扩展 swagger支持文档自动列举所有枚举值
承接上篇文章 《一站式解决使用枚举的各种痛点》 文章最后提到:在使用 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、实现 ParameterBuilderPlugin 和 OperationBuilderPlugin 接口,列举枚举参数的所有取值。
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支持文档自动列举所有枚举值的更多相关文章
- JAVA中自定义扩展Swagger的能力,自动生成参数取值含义说明,提升开发效率
大家好,又见面了. 在JAVA做前后端分离的项目开发的时候,服务端需要提供接口文档供周边人员做接口的对接指导.越来越多的项目都在尝试使用一些基于代码自动生成接口文档的工具来替代由开发人员手动编写接口文 ...
- springboot+swagger接口文档企业实践(上)
目录 1.引言 2.swagger简介 2.1 swagger 介绍 2.2 springfox.swagger与springboot 3. 使用springboot+swagger构建接口文档 3. ...
- .net core的Swagger接口文档使用教程(二):NSwag
上一篇介绍了Swashbuckle ,地址:.net core的Swagger接口文档使用教程(一):Swashbuckle 讲的东西还挺多,怎奈微软还推荐了一个NSwag,那就继续写吧! 但是和Sw ...
- .net core的Swagger接口文档使用教程(一):Swashbuckle
现在的开发大部分都是前后端分离的模式了,后端提供接口,前端调用接口.后端提供了接口,需要对接口进行测试,之前都是使用浏览器开发者工具,或者写单元测试,再或者直接使用Postman,但是现在这些都已经o ...
- 添加swagger api文档到node服务
swagger,一款api测试工具,详细介绍参考官网:http://swagger.io/ ,这里主要记录下怎么将swagger api应用到我们的node服务中: 1.任意新建node api项目, ...
- springboot成神之——swagger文档自动生成工具
本文讲解如何在spring-boot中使用swagger文档自动生成工具 目录结构 说明 依赖 SwaggerConfig 开启api界面 JSR 303注释信息 Swagger核心注释 User T ...
- springboot+swagger接口文档企业实践(下)
目录 1.引言 2. swagger接口过滤 2.1 按包过滤(package) 2.2 按类注解过滤 2.3 按方法注解过滤 2.4 按分组过滤 2.4.1 定义注解ApiVersion 2.4.2 ...
- Swagger API文档
Swagger API文档集中化注册管理 接口文档是前后端开发对接时很重要的一个组件.手动编写接口文档既费时,又存在文档不能随代码及时更新的问题,因此产生了像swagger这样的自动生成接口文档的 ...
- [BI项目记]-配置Sharepoint2013支持文档版本管理笔记
做开发或者做方案,写文档是很重要的一个工作,我们经常需要知道文档被修改的次数,谁在什么时间修改的文档,以及在某一个版本中,都修改了哪些内容,以及不同版本的文档之间有什么差别. 如何对文档进行版本管理, ...
随机推荐
- golang依赖管理
目录 使用GOPATH管理依赖 临时GOPATH 依赖查找路径 使用GOVENDER管理依赖 使用GO111MODULE管理依赖 Usage 常用命令列表 不常用命令 使用示例 开启GO111MODU ...
- 0day堆(2)堆的调试实验
堆的调试实验 调试态堆管理策略和常态堆管理策略:前者只使用空表不用块表,不真实 使用调试器加载函数会触发前者 __asm int3 调试最真实的栈 未启用块表的堆区信息 堆区起始位置(假设为0x005 ...
- xpath进阶用法
一.简介 xpath作为对网页.对xml文件进行定位的工具,速度快,语法简洁明了,在网络爬虫解析内容的过程中起到很大的作用,除了xpath的基础用法之外xpath中还存在着非常之多的进阶用法,本文将对 ...
- PHP $_FILES的应用
关于文件上传这块,如果处理不好的话,很容易成为黑客入侵的开口,例如黑客在你这个上传接口里放一段木马的文件,那只能祝你好运了. 所以,我们上传文件的时候都会先判断, 但是一般的操作是先上传,再判断,如果 ...
- 探索ORACLE之ASM概念(完整版)
探索ORACLE之ASM概念(完整版) 本文出自https://www.jb51.net/article/43527.htm ASM是Oracle 10g R2中为了简化Oracle数据库的管理而推出 ...
- Qt 的日期 时间
QDateTime 的构造函数,有参数是QDate的.这样就可以把日期转化成 QDateTime. QDateTime.toTime_t() 可以转化成 Unix 时间.
- Linux hostname主机名查看和设置
查询主机名: uname -n hostname [root@oldboy ~]# uname -n oldboy [root@oldboy ~]# hostname oldboy Linux操作系统 ...
- 数学--数论--HDU 5019 revenge of GCD
Revenge of GCD Problem Description In mathematics, the greatest common divisor (gcd), also known as ...
- P1468 派对灯 Party Lamps(BIG 模拟)
题目描述 在IOI98的节日宴会上,我们有N(10<=N<=100)盏彩色灯,他们分别从1到N被标上号码. 这些灯都连接到四个按钮: 按钮1:当按下此按钮,将改变所有的灯:本来亮着的灯就熄 ...
- 虚拟机部署单机版kubernetes,minikube,docker
# 目前公司用的是阿里云的容器服务 所以本地搭建个单机版 方便测试使用# VMware® Workstation 12 Pro 版本# 虚拟机环境配置:配置 2核 4G 网络桥接# 系统镜像: Cen ...