自定義枚舉 --- Swagger文檔展示

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

ps: 枚舉的定義參見 自定義枚舉 --- MyBatis字段映射

當(dāng)前

Springfox默認(rèn)枚舉

存在2個(gè)問題

  1. 類型顯示為string,需要修改為integer
  2. 枚舉的類型顯示為枚舉值,需要修改為枚舉的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)上資源特別少,建議收藏

自定義枚舉系列

參考

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,058評(píng)論 25 709
  • 星星點(diǎn)點(diǎn)下凡塵, 似寒實(shí)暖擾人心。 一覺醒來冬何處, 暮去朝來再迎春。
    八樓豬蹄閱讀 125評(píng)論 0 1
  • 你多關(guān)心別人也沒用,你也幫不了別人多少忙 對(duì)于身邊的人和事習(xí)慣了也不過如此,你保護(hù)不了自己也還是沒用 ...
    奈落兒閱讀 210評(píng)論 0 0
  • 對(duì)旅游城市來說,特別是對(duì)杭州來說,好像沒有淡旺季之說。它就像一個(gè)美人,一年四季都不同,你想要看它是什么樣子,它都不...
    七七媽媽是海綿閱讀 1,764評(píng)論 0 1

友情鏈接更多精彩內(nèi)容