问题:使用swagger作为api文档,但文档中的枚举类型仅显示枚举name,对于使用文档的人员来讲不容易理解
解决思路:枚举类型加上自定义的描述
<dependency>
<groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-models-jakarta</artifactId>
<version>2.2.8</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
<version>4.1.0</version>
</dependency>
@Bean
public PropertyCustomizer propertyCustomizer() {
return new PropertyCustomizer() {
@Override
public Schema customize(Schema property, AnnotatedType type) {
property.setName(StrUtil.toUnderlineCase(type.getPropertyName()));
if (!isEnumType(type)) {
return property;
}
Object[] enumConstants = ((SimpleType) type.getType()).getRawClass()
.getEnumConstants();
StringJoiner sj = new StringJoiner("");
sj.add(Optional.ofNullable(property.getDescription()).orElse(""))
.add(" ~ ")
.add(" 【 ");
for (Object enumConstant : enumConstants) {
Enum anEnum = (Enum) enumConstant;
String name = anEnum.name();
sj.add(name).add(":");
if (enumConstant instanceof BaseEnum dtoEnum) {
String desc = dtoEnum.getDesc();
sj.add(desc)
.add(";")
.add(" ");
}
}
sj.add("】");
property.setDescription(sj.toString());
return property;
}
};
}
private boolean isEnumType(AnnotatedType type) {
return Optional.ofNullable(type)
.map(AnnotatedType::getType)
.filter(s -> s instanceof SimpleType)
.map(s -> (SimpleType) s)
.map(SimpleType::getRawClass)
.map(clazz -> clazz.isEnum()
&& Stream.of(clazz.getInterfaces())
.anyMatch(s -> s.isAssignableFrom(BaseEnum.class)))
.orElse(Boolean.FALSE);
}
public interface BaseEnum<T> {
T getCode();
String getDesc();
}
public enum Level implements BaseEnum<String> {
JUNIOR("00", "初级"),
SENIOR("01", "高级"),
;
final String code;
final String desc;
Level(String code, String desc) {
this.code = code;
this.desc = desc;
}
@Override
public String getCode() {
return code;
}
@Override
public String getDesc() {
return desc;
}
}
参数字段描述中显示:【 JUNIOR:初级; SENIOR:高级; 】,可用值:JUNIOR,SENIOR
本文来自博客园,作者:IAyue,转载请注明原文链接:https://www.cnblogs.com/zmj-pr/p/18118699