首页 > 解决方案 > 如何将附加属性设置为布尔值

问题描述

我正在尝试将Additional Properties元素设置到 Open API Schema 3.X 中,但不幸的是,我无法在文档中找到任何可以帮助我的内容。我在 Spring Boot 中有一个应用程序,它使用依赖 Swagger OAS 作为传递依赖的 Spring doc OAS。让我在这里挑选一些代码片段:

@GetMapping("/{accountId}")
@Operation(summary = "Get account by account id", tags = TAG)
@ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "Return a specific account queried by path",
                content = { @Content(mediaType = "application/json",
                        schema = @Schema(implementation = AccountDetailsDTO.class)) }),
        @ApiResponse(responseCode = "404", description = "No accounts found",
                content = @Content) })
public ResponseEntity<AccountDetailsDTO> getAccountDetailsByClientId(@PathVariable("accountId") Integer accountId) { }

此属性默认为 true,我希望看到的是false,如下所示: 在此处输入图像描述

标签: javaspringspring-bootswaggeropenapi

解决方案


如果您想将属性显式设置为 false,则可以使用 TransformationFilter(注释为 Spring 的 @Component)将您规范的每个组件的附加属性设置为 false(如果您使用的是 Springfox)。

如果您使用的是 Springdoc,您可以添加一个 OpenApiCustomiser bean,请参阅示例

Springdoc OpenAPI 示例

    @Bean
    public OpenApiCustomiser openApiCustomiser() {
        return openApi -> openApi.getComponents().getSchemas().values().forEach( s -> s.setAdditionalProperties(false));
    }

Springfox 框架示例

@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
public class OpenApiTransformationFilter implements WebMvcOpenApiTransformationFilter
{
    public boolean supports(@NotNull DocumentationType delimiter)
    {
        return SwaggerPluginSupport.pluginDoesApply(delimiter);
    }

    @Override
    public OpenAPI transform(OpenApiTransformationContext<HttpServletRequest> context)
    {
        OpenAPI openApi = context.getSpecification();
        openApi.getComponents().getSchemas().values().forEach(schema -> schema.setAdditionalProperties(false));
        return openApi;
    }
}

推荐阅读