如何让Swagger UI显示POST请求体DTO中的必填字段?
解决Swagger UI请求体字段不显示必填标记的问题
问题根源
你错误地在DTO字段上使用了@Parameter注解——这个注解是用来描述路径/查询参数的,不适用于请求体中的DTO字段,所以Swagger无法识别该标记来展示必填状态。
正确解决方案
1. 修改DTO的注解配置
将字段上的@Parameter替换为@Schema(或结合JSR-380校验注解),让Swagger正确识别必填字段:
import io.swagger.v3.oas.annotations.media.Schema; import javax.validation.constraints.NotNull; @Schema(description = "My DTO") class VectorFoo { // 必填字段:@Schema标记文档必填,@NotNull实现后端校验 @NotNull @Schema(description = "my first attribute", required = true) private String attribute1; // 可选字段:默认非必填,可显式指定required=false @Schema(description = "my second attribute", required = false) private String attribute2; // getter/setter 保持不变 public String getAttribute1() { return attribute1; } public void setAttribute1(String attribute1) { this.attribute1 = attribute1; } public String getAttribute2() { return attribute2; } public void setAttribute2(String attribute2) { this.attribute2 = attribute2; } }
2. 简化REST端点注解(可选)
端点上的Swagger @RequestBody注解如果没有自定义需求可以省略,SpringDoc会自动识别Spring的@RequestBody:
@PostMapping("/fstVector") public ResponseEntity<VectorFoo> fstVPost( @RequestBody @Valid // 保留后端校验 final VectorFoo v1 ) { return new ResponseEntity<>(v1, HttpStatus.OK); }
额外说明
如果使用的SpringDoc版本在v1.5及以上,它会自动识别JSR-380的校验注解(如@NotNull、@NotEmpty),此时甚至可以不用显式添加@Schema(required = true),仅保留@NotNull就能让Swagger UI自动标记字段为必填。
内容的提问来源于stack exchange,提问作者jb62
相关产品推荐
相关产品推荐

