【问题标题】:OpenApi: Unable to override content type using OperationBuilderPluginOpenApi:无法使用 OperationBuilderPlugin 覆盖内容类型
【发布时间】:2021-09-22 12:58:49
【问题描述】:

我浪费了很多时间试图弄清楚如何在 SpringFox 生成的 api-docs 的输出中为我的 Spring 控制器设置默认 MediaType (案卷 openapi v3.0)。最后,我发现了一个几乎未记录的接口 OperationBuilderPlugin,理论上它允许我在 OperationContext 中设置一些属性,但不幸的是,虽然我正在寻找的属性似乎在操作已建立:

@Override
public void apply(OperationContext context) {
    context.operationBuilder()
            .produces(new LinkedHashSet<>(
                Collections.singletonList(MediaType.APPLICATION_JSON_VALUE)));
}

还尝试将 produces 直接设置到 Docket 中,但仍然没有成功

@Bean
public Docket api() {
    ....
    return new Docket(DocumentationType.OAS_30)
                .securityContexts(Collections.singletonList(securityContext()))
                .securitySchemes(Collections.singletonList(authenticationScheme))
                .useDefaultResponseMessages(true)
                .consumes(new HashSet<>(Arrays.asList(MediaType.APPLICATION_JSON_VALUE,
                        MediaType.APPLICATION_XML_VALUE)))
                .produces(new LinkedHashSet<>(Arrays.asList("application/json", "application/xml")))
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    ...
}

我不想在控制器类级别(或方法级别)指定返回 MediaType,所以如果我找不到更清洁的解决方案,我最后的机会是在我之后手动将 */* 替换为我想要的媒体类型从远程 url 下载 api-docs.json。

有人遇到过同样的问题吗? 任何帮助将不胜感激,在此先感谢

【问题讨论】:

    标签: spring-boot openapi springfox-boot-starter


    【解决方案1】:

    自己解决了。最后,我用另一个与原始类几乎相同的 bean MyResponseMessagesReader 覆盖了 bean ResponseMessagesReader,但是在下面的方法中,我更改了produces 的条件,在空集的情况下它添加了json媒体类型

    private void applyMyReturnTypeOverride(OperationContext context) {
     ...
          if (produces.isEmpty()) {
            produces.add(MediaType.APPLICATION_JSON);
          }
     ...
    }
    

    这是我能够进入操作创建过程的唯一联合点,也许有更好的方法(使用一些最简洁的策略实现 OperationBuilderPlugin),但我的时间正在为这个解决方案打勾。

    希望这可以帮助需要相同 API 生成行为的其他人

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-21
      • 2017-09-20
      • 2018-12-18
      • 1970-01-01
      • 2021-12-09
      • 1970-01-01
      • 1970-01-01
      • 2021-08-25
      相关资源
      最近更新 更多