SpringBoot OpenAPI中非基本类型对象无法显示nullable问题求助
问题:OpenAPI文档中嵌套DTO属性无法显示nullable标识
1. 定义的RespDTO模型
@Getter @Setter public class RespDTO implements Serializable{ /** * */ private static final long serialVersionUID = 1L; @Schema(nullable = true) private Long id; @Schema(nullable = true) private String otherId; @NotNull private String cod; @NotNull private String description; @Schema(nullable = true) private OtherDTO object; @NotNull private String idTransaction; }
2. 当前OpenAPI文档中的RespDTO展示
RespDTO: required: - cod - description - idTransaction type: object properties: id: type: integer format: int64 nullable: true otherId: type: string nullable: true cod: type: string description: type: string object: $ref: '#/components/schemas/OtherDTO' idTransaction: type: string
3. 问题说明
希望在OpenAPI文档中为OtherDTO类型的object属性显示nullable标识,但尝试以下方法均无效:
- 添加
@Schema(nullable = true)注解 - 添加
@Nullable注解 - 通过
io.swagger.v3.oas.models.OpenAPI手动设置该属性required为false
可行解决方案
调整@Schema注解配置
确保使用的swagger-core(或springdoc-openapi)版本在2.1.10及以上,给object属性的@Schema注解同时指定nullable = true和requiredMode = RequiredMode.NOT_REQUIRED:@Schema(nullable = true, requiredMode = RequiredMode.NOT_REQUIRED) private OtherDTO object;部分版本中仅设置
nullable不会触发OpenAPI文档的nullable标识,需要明确标记属性非必填。通过OpenAPI构建器直接修改属性
若手动设置required无效,可直接修改属性的nullable字段:@Bean public OpenAPI customOpenAPI() { Components components = new Components(); // 获取或创建RespDTO的Schema对象 Schema respDTOSchema = components.getSchemas().get("RespDTO"); if (respDTOSchema != null) { // 修改object属性的nullable设置 respDTOSchema.getProperties().get("object").setNullable(true); } return new OpenAPI().components(components); }检查嵌套DTO的定义
确认OtherDTO类本身没有被标记为强制必填(比如类上添加了@NotNull或@Schema(required = true)),否则会覆盖嵌套属性的nullable配置。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

