自定义枚举 --- Swagger文档展示

匿名 (未验证) 提交于 2019-12-02 23:43:01

在其它两篇文章中,已经解决的自定义枚举在MyBatis以及Rest接口的转换,但是在Springfox中还存在问题,不能使用code来作为api。本文通过扩展Springfox,实现了对自定义枚举的良好支持。

ps: 枚举的定义参见 自定义枚举 --- MyBatis字段映射

当前

Springfox默认枚举

存在2个问题

  1. 类型显示为string,需要修改为integer
  2. 枚举的类型显示为枚举值,需要修改为枚举的code值(CodedEnum的定义请参见其他文章)

扩展后

扩展Springfox后的枚举展示

实现方式

实现ModelPropertyBuilderPlugin接口,

@Component public class CodedEnumPropertyPlugin implements ModelPropertyBuilderPlugin {     @Override     public void apply(ModelPropertyContext context) {         Optional<ApiModelProperty> annotation = Optional.absent();          if (context.getAnnotatedElement().isPresent()) {             annotation = annotation.or(ApiModelProperties.findApiModePropertyAnnotation(context.getAnnotatedElement().get()));         }         if (context.getBeanPropertyDefinition().isPresent()) {             annotation = annotation.or(Annotations.findPropertyAnnotation(                     context.getBeanPropertyDefinition().get(),                     ApiModelProperty.class));         }         final Class<?> rawPrimaryType = context.getBeanPropertyDefinition().get().getRawPrimaryType();         //过滤得到目标类型         if (annotation.isPresent() && CodedEnum.class.isAssignableFrom(rawPrimaryType)) {             //获取CodedEnum的code值             CodedEnum[] values = (CodedEnum[]) rawPrimaryType.getEnumConstants();             final List<String> displayValues = Arrays.stream(values).map(codedEnum -> Integer.toString(codedEnum.getCode())).collect(Collectors.toList());             final AllowableListValues allowableListValues = new AllowableListValues(displayValues, rawPrimaryType.getTypeName());             //固定设置为int类型             final ResolvedType resolvedType = context.getResolver().resolve(int.class);             context.getBuilder().allowableValues(allowableListValues).type(resolvedType);         }     }      @Override     public boolean supports(DocumentationType documentationType) {         return true;     } }



作者:十毛tenmao
链接:https://www.jianshu.com/p/1ebe41c5f284
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!