在其它兩篇文章中,已經(jīng)解決的自定義枚舉在MyBatis以及Rest接口的轉(zhuǎn)換,但是在Springfox中還存在問題,不能使用code來作為api。本文通過擴(kuò)展Springfox,實(shí)現(xiàn)了對(duì)自定義枚舉的良好支持。
ps: 枚舉的定義參見 自定義枚舉 --- MyBatis字段映射
當(dāng)前

Springfox默認(rèn)枚舉
存在2個(gè)問題
- 類型顯示為string,需要修改為integer
- 枚舉的類型顯示為枚舉值,需要修改為枚舉的code值(
CodedEnum的定義請(qǐng)參見其他文章)
擴(kuò)展后

擴(kuò)展Springfox后的枚舉展示
實(shí)現(xiàn)方式
實(shí)現(xiàn)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();
//過濾得到目標(biāo)類型
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());
//固定設(shè)置為int類型
final ResolvedType resolvedType = context.getResolver().resolve(int.class);
context.getBuilder().allowableValues(allowableListValues).type(resolvedType);
}
}
@Override
public boolean supports(DocumentationType documentationType) {
return true;
}
}
ps: 這篇文章可能小眾,但是原創(chuàng)性特別高,同類的網(wǎng)上資源特別少,建議收藏