首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >自定义枚举 --- Swagger文档展示

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

作者头像
十毛
发布2019-03-27 11:41:17
2.4K0
发布2019-03-27 11:41:17
举报

在其它两篇文章中,已经解决的自定义枚举在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;
    }
}

ps: 这篇文章可能小众,但是原创性特别高,同类的网上资源特别少,建议收藏

自定义枚举系列

参考

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.10.09 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 当前
  • 扩展后
  • 实现方式
  • 自定义枚举系列
  • 参考
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档