swagger文档枚举类型描述

x33g5p2x  于9个月前 转载在 其他  
字(2.2k)|赞(0)|评价(0)|浏览(328)

背景:

问题:使用swagger作为api文档,但文档中的枚举类型仅显示枚举name,对于使用文档的人员来讲不容易理解
解决思路:枚举类型加上自定义的描述

解决方案

maven配置

  1. <dependency>
  2. <groupId>io.swagger.core.v3</groupId>
  3. <artifactId>swagger-models-jakarta</artifactId>
  4. <version>2.2.8</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.github.xiaoymin</groupId>
  8. <artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
  9. <version>4.1.0</version>
  10. </dependency>

swagger配置,自定义PropertyCustomizer,将实现BaseEnum接口的枚举类型desc字段作为枚举值的描述,使用BaseEnum的目的是保证枚举类中包含desc描述字段,便于统一获取

  1. @Bean
  2. public PropertyCustomizer propertyCustomizer() {
  3. return new PropertyCustomizer() {
  4. @Override
  5. public Schema customize(Schema property, AnnotatedType type) {
  6. property.setName(StrUtil.toUnderlineCase(type.getPropertyName()));
  7. if (!isEnumType(type)) {
  8. return property;
  9. }
  10. Object[] enumConstants = ((SimpleType) type.getType()).getRawClass()
  11. .getEnumConstants();
  12. StringJoiner sj = new StringJoiner("");
  13. sj.add(Optional.ofNullable(property.getDescription()).orElse(""))
  14. .add(" ~ ")
  15. .add(" 【 ");
  16. for (Object enumConstant : enumConstants) {
  17. Enum anEnum = (Enum) enumConstant;
  18. String name = anEnum.name();
  19. sj.add(name).add(":");
  20. if (enumConstant instanceof BaseEnum dtoEnum) {
  21. String desc = dtoEnum.getDesc();
  22. sj.add(desc)
  23. .add(";")
  24. .add(" ");
  25. }
  26. }
  27. sj.add("】");
  28. property.setDescription(sj.toString());
  29. return property;
  30. }
  31. };
  32. }
  33. private boolean isEnumType(AnnotatedType type) {
  34. return Optional.ofNullable(type)
  35. .map(AnnotatedType::getType)
  36. .filter(s -> s instanceof SimpleType)
  37. .map(s -> (SimpleType) s)
  38. .map(SimpleType::getRawClass)
  39. .map(clazz -> clazz.isEnum()
  40. && Stream.of(clazz.getInterfaces())
  41. .anyMatch(s -> s.isAssignableFrom(BaseEnum.class)))
  42. .orElse(Boolean.FALSE);
  43. }
  1. public interface BaseEnum<T> {
  2. T getCode();
  3. String getDesc();
  4. }

枚举demo

  1. public enum Level implements BaseEnum<String> {
  2. JUNIOR("00", "初级"),
  3. SENIOR("01", "高级"),
  4. ;
  5. final String code;
  6. final String desc;
  7. Level(String code, String desc) {
  8. this.code = code;
  9. this.desc = desc;
  10. }
  11. @Override
  12. public String getCode() {
  13. return code;
  14. }
  15. @Override
  16. public String getDesc() {
  17. return desc;
  18. }
  19. }

文档效果:

参数字段描述中显示:【 JUNIOR:初级; SENIOR:高级; 】,可用值:JUNIOR,SENIOR

本文来自博客园,作者:IAyue,转载请注明原文链接:https://www.cnblogs.com/zmj-pr/p/18118699

相关文章