Custom enumeration --- Swagger documents show

 

In the other two articles, has been resolved in MyBatis custom enumeration and convert Rest interfaces, but there are still problems in Springfox, the code can not be used as an api. By extension Springfox, to achieve a custom enumeration good support.

ps: see the definition of enumeration custom field mapping enumeration --- MyBatis

current

 
Springfox default enumeration

There are two problems

  1. Type is shown as string, you need to modify the integer
  2. Enumerated type is shown as an enumeration value, you need to modify the code value enumeration ( CodedEnumdefinition see other article)

After expansion

 
The expanded Springfox enumeration show

Method to realize

Implement ModelPropertyBuilderPlugininterfaces,

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

 



Author: Ten hair tenmao
link: https: //www.jianshu.com/p/1ebe41c5f284
Source: Jane book
Jane book copyright reserved by the authors, are reproduced in any form, please contact the author to obtain authorization and indicate the source.

 

Guess you like

Origin www.cnblogs.com/softidea/p/11025735.html