由于springfox-swagger2的實(shí)現(xiàn)的問題,程序只能配置為按照英文字母排序。不過我們可以通過編寫插件實(shí)現(xiàn)字段按類變量定義順序排序。具體插件代碼為
import static springfox.documentation.schema.Annotations.findPropertyAnnotation;
import static springfox.documentation.swagger.schema.ApiModelProperties.findApiModePropertyAnnotation;
import java.lang.reflect.Field;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.introspect.AnnotatedField;
import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition;
import com.google.common.base.Optional;
import io.swagger.annotations.ApiModelProperty;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.schema.ModelPropertyBuilderPlugin;
import springfox.documentation.spi.schema.contexts.ModelPropertyContext;
import springfox.documentation.swagger.common.SwaggerPluginSupport;
@Component
public class CustomApiModelPropertyPositionBuilder implements ModelPropertyBuilderPlugin {
? ? private Log log = LogFactory.getLog(getClass());
? ? @Override
? ? public boolean supports(DocumentationType delimiter) {
? ? ? ? return SwaggerPluginSupport.pluginDoesApply(delimiter);
? ? }
? ? @Override
? ? public void apply(ModelPropertyContext context) {
? ? ? ? Optional<BeanPropertyDefinition> beanPropertyDefinitionOpt = context.getBeanPropertyDefinition();
? ? ? ? Optional<ApiModelProperty> annotation = Optional.absent();
? ? ? ? if (context.getAnnotatedElement().isPresent()) {
? ? ? ? ? ? annotation = annotation.or(findApiModePropertyAnnotation(context.getAnnotatedElement().get()));
? ? ? ? }
? ? ? ? if (context.getBeanPropertyDefinition().isPresent()) {
? ? ? ? ? ? annotation = annotation.or(findPropertyAnnotation(context.getBeanPropertyDefinition().get(), ApiModelProperty.class));
? ? ? ? }
? ? ? ? if (beanPropertyDefinitionOpt.isPresent()) {
? ? ? ? ? ? BeanPropertyDefinition beanPropertyDefinition = beanPropertyDefinitionOpt.get();
? ? ? ? ? ? if (annotation.isPresent() && annotation.get().position() != 0) {
? ? ? ? ? ? ? ? return;
? ? ? ? ? ? }
? ? ? ? ? ? AnnotatedField field = beanPropertyDefinition.getField();
? ? ? ? ? ? Class<?> clazz = field.getDeclaringClass();
? ? ? ? ? ? Field[] declaredFields = clazz.getDeclaredFields();
? ? ? ? ? ? Field declaredField;
? ? ? ? ? ? try {
? ? ? ? ? ? ? ? declaredField = clazz.getDeclaredField(field.getName());
? ? ? ? ? ? } catch (NoSuchFieldException | SecurityException e) {
? ? ? ? ? ? ? ? log.error("", e);
? ? ? ? ? ? ? ? return;
? ? ? ? ? ? }
? ? ? ? ? ? int indexOf = ArrayUtils.indexOf(declaredFields, declaredField);
? ? ? ? ? ? if (indexOf != -1) {
? ? ? ? ? ? ? ? context.getBuilder().position(indexOf);
? ? ? ? ? ? }
? ? ? ? }
? ? }
}
但手熟爾
如果出現(xiàn)問題,應(yīng)為版本問題。自己研究如何在當(dāng)前版本寫一個(gè)插件實(shí)現(xiàn)。