【问题标题】:How to change default schema of LocalDateTime in Swagger documentation using springdoc?如何使用 springdoc 在 Swagger 文档中更改 LocalDateTime 的默认模式?
【发布时间】:2021-09-19 20:50:17
【问题描述】:

我们使用 Spring Boot 和https://springdoc.org/ 来生成 OpenApi 文档。我们想更改 LocalDateTime 的默认模式,因此每次使用 LocalDateTime 时我们都没有相同的注释。所以,我补充说:

    static { 
        SpringDocUtils.getConfig().replaceWithSchema(LocalDateTime.class, 
                new StringSchema().example("2021-07-05T10:35:17.000").pattern("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}[.]\\d{3}")); 
    } 

成功了。问题是现在无法为特定字段添加自定义描述或示例:

    @Schema(description = "important date") 
    private LocalDateTime aDate; 

如您所见,Swagger-UI 中缺少以下描述: screenshot with missing description

可以解决吗?是否有另一种方法可以为 LocalDateTime 设置默认自定义架构?

【问题讨论】:

    标签: java spring-boot swagger springdoc


    【解决方案1】:

    你可以使用 OpenAPICustomerCustomiser

    @Bean
    public OpenApiCustomiser openAPICustomiser() {​​​​​​​​​
        return openApi -> {​​​​​​​​​
            openApi.getComponents().getSchemas().forEach((s, schema) -> {​​​​​​​​​
                Map<String, Schema> properties = schema.getProperties();
                if (properties == null) {​​​​​​​​​
                    properties = Map.of();
                }​​​​​​​​​
                for (String propertyName : properties.keySet()) {​​​​​​​​​
                    Schema propertySchema = properties.get(propertyName);
                    if (propertySchema instanceof DateTimeSchema) {​​​​​​​​​
                        properties.replace(propertyName, new StringSchema()
                                .example("2021-07-05T10:35:17.000")
                                .pattern("^\\d{​​​​​​​​​4}​​​​​​​​​-\\d{​​​​​​​​​2}​​​​​​​​​-\\d{​​​​​​​​​2}​​​​​​​​​T\\d{​​​​​​​​​2}​​​​​​​​​:\\d{​​​​​​​​​2}​​​​​​​​​:\\d{​​​​​​​​​2}​​​​​​​​​[.]\\d{​​​​​​​​​3}​​​​​​​​​$")
                                //copies original description
                                .description(propertySchema.getDescription()));
                    }​​​​​​​​​
                }​​​​​​​​​
            }​​​​​​​​​);
        }​​​​​​​​​;
    }​​​​​​​​​
    

    【讨论】:

      猜你喜欢
      • 2018-12-14
      • 2020-12-16
      • 1970-01-01
      • 1970-01-01
      • 2019-03-15
      • 2019-12-03
      • 2020-12-04
      • 2018-05-17
      • 1970-01-01
      相关资源
      最近更新 更多