Springfox 添加全局响应

1,415 阅读1分钟

使用场景

主要用于系统需要针对特定http status进行统一返回时配置,可以针对不同的http method进行定义。

使用方式

  1. 定义Response对象,如果返回的对象需要配置返回对象的包路径,否则生成的swagger文档无法正确映射此对象
           Response serverErrorResponse = new ResponseBuilder()
                .code("500").description("Internal Server Error")
                .representation(MediaType.APPLICATION_JSON)
                .apply(r ->
                        r.model(m ->
                                m.referenceModel(ref ->
                                        ref.key(key ->
                                                key.isResponse(true)
                                                        .qualifiedModelName(q -> q.name("R").namespace("com.example.gsd")))
                                )))
                .build();

需要注意,如果响应类型为对象类型,在定义ModelKey时,qualifiedModelName需要为对应对象的包路径和名称,同时需要在定义Docket时使用addtionalModles方法添加对应的类型。

  1. 在Docket定义时添加定义的全局响应和响应中模型
new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .globalResponses(HttpMethod.POST, globalResponse())
                .groupName(swaggerProperties.getGroupName())
                .additionalModels(typeResolver.resolve(R.class))
                .select()
                .build();