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;
    }
}

效果

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM