在其它兩篇文章中,已經解決的自定義枚舉在MyBatis以及Rest接口的轉換,但是在Springfox中還存在問題,不能使用code來作為api。本文通過擴展Springfox,實現了對自定義枚舉的良好支持。
ps: 枚舉的定義參見 自定義枚舉 --- MyBatis字段映射
當前

Springfox默認枚舉
存在2個問題
- 類型顯示為string,需要修改為integer
- 枚舉的類型顯示為枚舉值,需要修改為枚舉的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
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯系作者獲得授權並注明出處。