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
![](http://upload-images.jianshu.io/upload_images/7081994-d2ce686d0e9ae68c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/522/format/webp)
Springfox default enumeration
There are two problems
- Type is shown as string, you need to modify the integer
- Enumerated type is shown as an enumeration value, you need to modify the code value enumeration (
CodedEnum
definition see other article)
After expansion
![](http://upload-images.jianshu.io/upload_images/7081994-5cc8da40f136f966.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/524/format/webp)
The expanded Springfox enumeration show
Method to realize
Implement ModelPropertyBuilderPlugin
interfaces,
@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.