如何让OpenAPI Generator将验证注解生成在字段而非Getter方法上
解决OpenAPI Generator生成Spring代码时验证注解在Getter而非字段上的问题
在你的openApiGenerate配置中添加两个关键配置项,即可让@Valid、@NotNull等验证注解生成在字段上:
openApiGenerate { generatorName.set("spring") openApiGenerators.include.set(listOf("spring")) configOptions.set(mapOf( "dateLibrary" to "java8", "interfaceOnly" to "true", "useTags" to "true", "useBeanValidation" to "true", "beanValidationAnnotationsOnFields" to "true" )) }
配置说明:
useBeanValidation:确保启用Bean Validation注解生成,虽然默认值通常为true,显式声明可避免版本差异导致的异常。beanValidationAnnotationsOnFields:核心配置项,指定将验证注解从Getter方法转移到实体类的字段上,这样Controller层的参数校验就能正常触发。
重新执行代码生成任务后,你定义的Request类会变成类似这样的结构:
public class Request { @NotNull private String fieldOne; @NotNull @Valid private Data fieldTwo; // Getter、Setter方法 }
此时Controller中对@Valid @RequestBody Request request的参数校验就能正常生效。
内容的提问来源于stack exchange,提问作者AnnKont
相关产品推荐
相关产品推荐

