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


    在其它两篇文章中,已经解决的自定义枚举在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
    来源:简书
    简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
  • 相关阅读:
    PHP学习九--会话控制session和cookie
    PHP学习八--正则表达式
    PHP学习六--类和对象
    PHP学习五--函数
    PHP学习四--数组
    《30天自制操作系统》day08——鼠标控制与32位模式切换
    java 中 静态块的作用
    学习(一)
    asp中 grideview 更新 无法获取值 解决办法
    ASP.NET中的GridView自带的编辑更新功能
  • 原文地址:https://www.cnblogs.com/softidea/p/11025735.html
Copyright © 2020-2023  润新知