zoukankan      html  css  js  c++  java
  • Swagger展示枚举类型参数

    实现原理:修改@ApiModelProperty的属性:value、dataType、allowableValues

    @Component
    public class SwaggerDisplayConfig implements ModelPropertyBuilderPlugin {
        @Override
        public void apply(ModelPropertyContext context) {
            AnnotatedField field = context.getBeanPropertyDefinition().get().getField();
            Class<?> rawType = field.getRawType();
            if (!rawType.isEnum()) {
                return;
            }
            ApiModelProperty annotation = field.getAnnotation(ApiModelProperty.class);
            // Annotation是通过代理来设置并存储属性值的
            InvocationHandler ih = Proxy.getInvocationHandler(annotation);
            try {
                // Annotation所有属性的值都存储在InvocationHandler的memberValues属性,该属性类型为Map
                Field memberValuesField = ih.getClass().getDeclaredField("memberValues");
                memberValuesField.setAccessible(true);
                Map memberValues = (Map)memberValuesField.get(ih);
                String className = rawType.getDeclaredField("value").getType().getName();
                memberValues.put("dataType", className);
                Object[] enumConstants = rawType.getEnumConstants();
                Method getValue = rawType.getMethod("getValue");
                Method getDesc = rawType.getMethod("getDesc");
                List<String> descriptions = new ArrayList<>();
                List<String> allowableValues = new ArrayList<>();
                for (Object e : enumConstants){
                    String v = getValue.invoke(e).toString();
                    allowableValues.add(v);
                    descriptions.add(v + ":" + getDesc.invoke(e));
                }
                memberValues.put("value", ((String)memberValues.get("value")).concat("。").concat(String.join(",", descriptions)));
                memberValues.put("allowableValues", String.join(",", allowableValues));
            } catch (NoSuchFieldException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    
        @Override
        public boolean supports(DocumentationType documentationType) {
            return true;
        }
    }

    效果

  • 相关阅读:
    理解Java虚拟机——Java内存模型管理
    Java 使用fastjson 将 json字符串写到文件中去
    java 如何调用 linux or mac 命令行
    MacOS 编译 openjdk8 并导入 Clion 调试
    linux ls 命令超级详解
    小 Q 与树 (点分治)
    mysql 索引策略
    java中serialVersionUID作用
    通过源码分析Spring Security用户认证流程
    使用PowerMockRunner和Mockito编写单元测试用例详解
  • 原文地址:https://www.cnblogs.com/joequa/p/14113805.html
Copyright © 2011-2022 走看看