springfox + swagger2自定義JsonObject/Map參數(shù)文檔

說(shuō)明

該改動(dòng)不影響swagger原來(lái)的使用,Object/JsonObject 都可以兼容

Controller

image.png

Model

image.png

最終結(jié)果

request:


image.png

request model:


image.png

response:


image.png

response model:


image.png

代碼實(shí)現(xiàn)

首先根據(jù)官方文檔穗泵,寫(xiě)一個(gè)OperationBuilderPlugin類型的插件养晋,這個(gè)插件用來(lái)讀取接口的參數(shù)

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ParametersReader implements OperationBuilderPlugin {
...
 @Override
 public void apply(OperationContext context) {
        context.operationBuilder().parameters(readParameters(context));
 }
 private List<Parameter> readParameters(OperationContext context) {
        List<Parameter> parameters = Lists.newArrayList();
        List<ResolvedMethodParameter> methodParameters = context.getParameters();

        //1. 先讀取GlobalString類中我們定義的參數(shù)單元亲怠,用一個(gè)Map來(lái)保存
        Map<String, ApiSingleParam> paramMap = new HashMap<>();
        Field[] fields = GlobalString.class.getDeclaredFields();
        String type = new String();
        for (Field field : fields) {
            if (field.isAnnotationPresent(ApiSingleParam.class)) {
                ApiSingleParam param = field.getAnnotation(ApiSingleParam.class);
                try {
                    String name = (String) field.get(type);
                    paramMap.put(name, param);
                } catch (Exception e) {
                }
            }
        }

        //遍歷controller中的方法
        for (ResolvedMethodParameter methodParameter : methodParameters) {
            ParameterContext parameterContext = new ParameterContext(methodParameter,
                    new ParameterBuilder(),
                    context.getDocumentationContext(),
                    context.getGenericsNamingStrategy(),
                    context);
            Function<ResolvedType, ? extends ModelReference> factory = createModelRefFactory(parameterContext);

            //讀取自定義的注釋類
            Optional<ApiJsonObject> annotation = context.findAnnotation(ApiJsonObject.class);

            if (annotation.isPresent()) {
                //2. 自定義的注釋類里包含參數(shù)列表,我們把它合成一個(gè)請(qǐng)求Model和應(yīng)答Model缘琅,放在ModelCache緩存里面
                ModelCache.getInstance().setFactory(factory)
                        .setParamMap(paramMap)
                        .addModel(annotation.get());
            }
        }
        return parameters;
    }
}

然后重寫(xiě) ApiListingScanner 類,將我們的Model加入到swagger的Model列表中

@Component
@Primary
public class ApiListingPluginsScanner extends ApiListingScanner {
...
    public Multimap<String, ApiListing> scan(ApiListingScanningContext context) {
         final Multimap<String, ApiListing> apiListingMap = LinkedListMultimap.create();
        int position = 0;
        Map<ResourceGroup, List<RequestMappingContext>> requestMappingsByResourceGroup
                = context.getRequestMappingsByResourceGroup();
        Collection<ApiDescription> additionalListings = pluginsManager.additionalListings(context);
        Set<ResourceGroup> allResourceGroups = FluentIterable.from(collectResourceGroups(additionalListings))
                .append(requestMappingsByResourceGroup.keySet())
                .toSet();

        List<SecurityReference> securityReferences = newArrayList();
        for (final ResourceGroup resourceGroup : sortedByName(allResourceGroups)) {

            DocumentationContext documentationContext = context.getDocumentationContext();
            Set<String> produces = new LinkedHashSet<String>(documentationContext.getProduces());
            Set<String> consumes = new LinkedHashSet<String>(documentationContext.getConsumes());
            String host = documentationContext.getHost();
            Set<String> protocols = new LinkedHashSet<String>(documentationContext.getProtocols());
            Set<ApiDescription> apiDescriptions = newHashSet();

            Map<String, Model> models = new LinkedHashMap<String, Model>();
            List<RequestMappingContext> requestMappings = nullToEmptyList(requestMappingsByResourceGroup.get(resourceGroup));

            for (RequestMappingContext each : sortedByMethods(requestMappings)) {//url
                Map<String, Model> knownModels = new HashMap<>();
                models.putAll(apiModelReader.read(each.withKnownModels(models)));
                apiDescriptions.addAll(apiDescriptionReader.read(each));
            }
            //加入自己的Model
            models.putAll(ModelCache.getInstance().getKnownModels());

            List<ApiDescription> additional = from(additionalListings)
                    .filter(and(
                                    belongsTo(resourceGroup.getGroupName()),
                                    onlySelectedApis(documentationContext)))
                    .toList();
            apiDescriptions.addAll(additional);

            List<ApiDescription> sortedApis = FluentIterable.from(apiDescriptions)
                    .toSortedList(documentationContext.getApiDescriptionOrdering());
            Optional<String> o = longestCommonPath(sortedApis);
            String resourcePath = new ResourcePathProvider(resourceGroup)
                    .resourcePath()
                    .or(o)
                    .orNull();

            PathProvider pathProvider = documentationContext.getPathProvider();
            String basePath = pathProvider.getApplicationBasePath();
            PathAdjuster adjuster = new PathMappingAdjuster(documentationContext);
            ApiListingBuilder apiListingBuilder = new ApiListingBuilder(context.apiDescriptionOrdering())
                    .apiVersion(documentationContext.getApiInfo().getVersion())
                    .basePath(adjuster.adjustedPath(basePath))
                    .resourcePath(resourcePath)
                    .produces(produces)
                    .consumes(consumes)
                    .host(host)
                    .protocols(protocols)
                    .securityReferences(securityReferences)
                    .apis(sortedApis)
                    .models(models)
                    .position(position++)
                    .availableTags(documentationContext.getTags());

            ApiListingContext apiListingContext = new ApiListingContext(
                    context.getDocumentationType(),
                    resourceGroup,
                    apiListingBuilder);
            apiListingMap.put(resourceGroup.getGroupName(), pluginsManager.apiListing(apiListingContext));
        }
        return apiListingMap;
    }
}

這樣request的部分就完成了褒颈,下面是response的實(shí)現(xiàn)

先重寫(xiě) SwaggerResponseMessageReader 類

@Primary
@Component
@Order(SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER + 3)//一定要大一點(diǎn)
public class ResponseMessageReader extends SwaggerResponseMessageReader {
    
    private final TypeNameExtractor typeNameExtractor;
    private final TypeResolver typeResolver;

    public ResponseMessageReader(TypeNameExtractor typeNameExtractor, TypeResolver typeResolver) {
        super(typeNameExtractor, typeResolver);
        this.typeNameExtractor = typeNameExtractor;
        this.typeResolver = typeResolver;
    }

    @Override
    protected Set<ResponseMessage> read(OperationContext context) {
        ResolvedType defaultResponse = context.getReturnType();
        Optional<ApiOperation> operationAnnotation = context.findAnnotation(ApiOperation.class);
        Optional<ResolvedType> operationResponse =
                operationAnnotation.transform(resolvedTypeFromOperation(typeResolver, defaultResponse));
        Optional<ResponseHeader[]> defaultResponseHeaders = operationAnnotation.transform(responseHeaders());
        Map<String, Header> defaultHeaders = newHashMap();
        if (defaultResponseHeaders.isPresent()) {
            defaultHeaders.putAll(headers(defaultResponseHeaders.get()));
        }

        List<ApiResponses> allApiResponses = context.findAllAnnotations(ApiResponses.class);
        Set<ResponseMessage> responseMessages = newHashSet();

        Map<Integer, ApiResponse> seenResponsesByCode = newHashMap();
        for (ApiResponses apiResponses : allApiResponses) {
            ApiResponse[] apiResponseAnnotations = apiResponses.value();
            for (ApiResponse apiResponse : apiResponseAnnotations) {

                if (!seenResponsesByCode.containsKey(apiResponse.code())) {
                    seenResponsesByCode.put(apiResponse.code(), apiResponse);

                    java.util.Optional<ModelReference> responseModel = java.util.Optional.empty();
                    java.util.Optional<ResolvedType> type = resolvedType(null, apiResponse);
                    if (isSuccessful(apiResponse.code())) {
                        type = java.util.Optional.ofNullable(type.orElseGet(operationResponse::get));
                    }
                    if (type.isPresent()) {
                        //將返回的模型ID修改成自定義的,這里我取@apiResponse中的reference參數(shù)加"-result"組合
                        responseModel = java.util.Optional.of(new ModelRef(apiResponse.reference()+"-result"));
                    }
                    Map<String, Header> headers = newHashMap(defaultHeaders);
                    headers.putAll(headers(apiResponse.responseHeaders()));

                    responseMessages.add(new ResponseMessageBuilder()
                            .code(apiResponse.code())
                            .message(apiResponse.message())
                            .responseModel(responseModel.orElse(null))
                            .headersWithDescription(headers)
                            .build());
                }
            }
        }
        if (operationResponse.isPresent()) {
            ModelContext modelContext = returnValue(
                    context.getGroupName(),
                    operationResponse.get(),
                    context.getDocumentationType(),
                    context.getAlternateTypeProvider(),
                    context.getGenericsNamingStrategy(),
                    context.getIgnorableParameterTypes());
            ResolvedType resolvedType = context.alternateFor(operationResponse.get());

            ModelReference responseModel = modelRefFactory(modelContext, typeNameExtractor).apply(resolvedType);
            context.operationBuilder().responseModel(responseModel);
            ResponseMessage defaultMessage = new ResponseMessageBuilder()
                    .code(httpStatusCode(context))
                    .message(message(context))
                    .responseModel(responseModel)
                    .build();
            if (!responseMessages.contains(defaultMessage) && !"void".equals(responseModel.getType())) {
                responseMessages.add(defaultMessage);
            }
        }

        return responseMessages;
    }
    ...
}

ModelCache生成Model


    public ModelCache addModel(ApiJsonObject jsonObj) {
        String modelName =jsonObj.name();

        knownModels.put(modelName,
                new Model(modelName,
                        modelName,
                        new TypeResolver().resolve(String.class),
                        "xin.bee.model.entity.BusinessUser",
                        toPropertyMap(jsonObj.value()),
                        "POST參數(shù)",
                        "",
                        "",
                        newArrayList(), null, null
                ));
        String resultName = jsonObj.name() + "-" + "result";

        knownModels.put(resultName,
                new Model(resultName,
                        resultName,
                        new TypeResolver().resolve(String.class),
                        "xin.bee.model.entity.BusinessUser",
                        toResultMap(jsonObj.result(), resultName),
                        "返回模型",
                        "",
                        "",
                        newArrayList(), null, null
                ));
        return ModelCacheSub.instance;
    }

ModelProperty的制作

  ModelProperty mp = new ModelProperty(
                        jsonResult.name(),
                        type,
                        "",
                        0,
                        false,
                        false,
                        true,
                        false,
                        "",
                        null,
                        "",
                        null,
                        "",
                        null,
                        newArrayList()
                );// new AllowableRangeValues("1", "2000"),//.allowableValues(new AllowableListValues(["ABC", "ONE", "TWO"], "string"))
                mp.updateModelRef(getModelRef());
                ResolvedType collectionElementType = collectionElementType(type);
                try {
                    Field f = ModelProperty.class.getDeclaredField("modelRef");
                    f.setAccessible(true);
                    f.set(mp, new ModelRef("List",new ModelRef(subModelName)));
                } catch (Exception e) {
                    e.printStackTrace();
                }

這樣就搞定了M堑邸C着觥!

Map

map的話比較簡(jiǎn)單购城,參考這篇
https://blog.csdn.net/hellopeng1/article/details/82227942

git:https://github.com/cyjishuang/swagger-mode

jar:
build.gradle:

allprojects {
    repositories {
        //maven{ url 'http://maven.aliyun.com/nexus/content/groups/public/'}
        maven{ url "https://oss.sonatype.org/content/groups/staging"}
        //mavenCentral()
    }
}
dependencies {
    compile  group: 'io.github.cyjishuang' ,name: 'swagger-mode', version: '1.0'
}

spring-context.xml 添加掃描

    <context:component-scan base-package="io.github.cyjishuang"/>

在創(chuàng)建文檔的時(shí)候設(shè)置存放參數(shù)的類ModelCache.getInstance().setParamClass(XXX.class);

 public Docket createRestApi() {
        ModelCache.getInstance().setParamClass(GlobalString.class);
        return new Docket(DocumentationType.SWAGGER_2)...

這樣配置就完成了吕座,后面只需要對(duì)Controller和參數(shù)的類添加說(shuō)明即可,示例

@RequestMapping(value = "/api/v1/manager")
@RestController
@Api(description = "管理員身份接口")
public class ManagerController {
   @ApiOperation(value = "管理員-預(yù)判是否存在",notes ="預(yù)判管理員是否存在" )
    @ApiJsonObject(name = "manager-checkManager", value = {
            @ApiJsonProperty(name = JSON_USER_NAME),
            @ApiJsonProperty(name = JSON_USER_EMAIL)},
            result = @ApiJsonResult({}))
    @ApiImplicitParam(name = "params", required = true, dataType = "manager-checkManager")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", reference = "manager-checkManager")})

    @RequestMapping(value = "/checkManager", method = RequestMethod.POST, consumes = MSG_FORMAT_JSON_UTF8, produces = MSG_FORMAT_JSON_UTF8)
    public String checkManager(@RequestBody String params) {
        return new ControllerCallBack()
                .addCommonService(managerService::checkUser)
                .build(params);
    }
}
public class GlobalString {
    @ApiSingleParam(value = "用戶姓名", example = "test1")
    public static final String JSON_USER_NAME = "userName";

    @ApiSingleParam(value = "用戶郵箱", example = "17721026877@qq.com")
    public static final String JSON_USER_EMAIL = "userEmail";

    @ApiSingleParam(value = "錯(cuò)誤碼", example = "0", type = Integer.class)
    public static final String JSON_ERROR_CODE = "errorCode";

    @ApiSingleParam(value = "錯(cuò)誤信息", example = "OK")
    public static final String JSON_ERROR_MSG = "errorMsg";
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末瘪板,一起剝皮案震驚了整個(gè)濱河市吴趴,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌侮攀,老刑警劉巖锣枝,帶你破解...
    沈念sama閱讀 212,718評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異兰英,居然都是意外死亡撇叁,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,683評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門畦贸,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)陨闹,“玉大人,你說(shuō)我怎么就攤上這事∏骼鳎” “怎么了泡一?”我有些...
    開(kāi)封第一講書(shū)人閱讀 158,207評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)觅廓。 經(jīng)常有香客問(wèn)我,道長(zhǎng)涵但,這世上最難降的妖魔是什么杈绸? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 56,755評(píng)論 1 284
  • 正文 為了忘掉前任,我火速辦了婚禮矮瘟,結(jié)果婚禮上瞳脓,老公的妹妹穿的比我還像新娘。我一直安慰自己澈侠,他們只是感情好劫侧,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,862評(píng)論 6 386
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著哨啃,像睡著了一般烧栋。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上拳球,一...
    開(kāi)封第一講書(shū)人閱讀 50,050評(píng)論 1 291
  • 那天审姓,我揣著相機(jī)與錄音,去河邊找鬼祝峻。 笑死魔吐,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的莱找。 我是一名探鬼主播酬姆,決...
    沈念sama閱讀 39,136評(píng)論 3 410
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼奥溺!你這毒婦竟也來(lái)了辞色?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 37,882評(píng)論 0 268
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤浮定,失蹤者是張志新(化名)和其女友劉穎淫僻,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體壶唤,經(jīng)...
    沈念sama閱讀 44,330評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡雳灵,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,651評(píng)論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了闸盔。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片悯辙。...
    茶點(diǎn)故事閱讀 38,789評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出躲撰,到底是詐尸還是另有隱情针贬,我是刑警寧澤,帶...
    沈念sama閱讀 34,477評(píng)論 4 333
  • 正文 年R本政府宣布拢蛋,位于F島的核電站桦他,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏谆棱。R本人自食惡果不足惜快压,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,135評(píng)論 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望垃瞧。 院中可真熱鬧蔫劣,春花似錦、人聲如沸个从。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,864評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)嗦锐。三九已至嫌松,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間奕污,已是汗流浹背豆瘫。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,099評(píng)論 1 267
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留菊值,地道東北人外驱。 一個(gè)月前我還...
    沈念sama閱讀 46,598評(píng)論 2 362
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像腻窒,于是被迫代替她去往敵國(guó)和親昵宇。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,697評(píng)論 2 351

推薦閱讀更多精彩內(nèi)容