如何从SpringFox向生成的Swagger json添加自定义字段?

时间:2018-06-21 14:30:15

标签: swagger springfox

我正在尝试将字段externalDocs添加到Springfox的generated Json中:

"externalDocs": {
    "description": "find more info here",
    "url": "https://swagger.io/about"
},

通过阅读SpringFox文档,我了解我需要创建一个plugin来扩展SpringFox功能并添加此字段。我尝试过:

@Component
@Order(SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER + 1002)
@Slf4j
public class ExternalDocSwaggerConfiguration implements ApiListingBuilderPlugin {

    @Override
    public void apply(final ApiListingContext apiListingContext) {

        ObjectVendorExtension ext = new ObjectVendorExtension("externalDocs");
        ext.addProperty(new StringVendorExtension("description", "Link externo"));
        ext.addProperty(new StringVendorExtension("url", "https://swagger.io/about"));
        apiListingContext.apiListingBuilder().extensions(
            Collections.singletonList(ext)); // extensions does not exist
    }

    @Override
    public boolean supports(final DocumentationType documentationType) {
        return true;
    }
}

我本来希望将扩展名添加到OperationBuilderPlugin中,如图here所示,但是extensions上没有apiListingBuilder方法。

那么,如何使用SpringFox将此标签添加到生成的Swagger Json的根上?

1 个答案:

答案 0 :(得分:2)

版本2.7.0添加了this feature

要添加此字段externalDocs,可以使用extensions中的Docket方法:

@Bean
public Docket customImplementation() {

    ObjectVendorExtension ext = new ObjectVendorExtension("externalDocs");
    ext.addProperty(new StringVendorExtension("description", "Link externo"));
    ext.addProperty(new StringVendorExtension("url", "https://swagger.io/about"));

    return new Docket(DocumentationType.SWAGGER_2)
            .extensions(Collections.singletonList(ext))
            .apiInfo(apiInfo())
            .securitySchemes(newArrayList(apiKey()))
            .pathMapping("/api")
            .securityContexts(newArrayList(securityContext())).select()
            .apis(getPackages())
            .paths(PathSelectors.any())
            .build();
}