SpringFox Swagger生成数组项minLength/maxLength属性不生效问题问询
背景
我在DTO中定义了如下字符串列表字段:
@ApiModelProperty(value = "A list of strings") @JsonProperty("STRING_LIST") private List<@Size(max = 4) String> myStringList;
我通过添加@Size(max = 4)注解,期望限制列表内每个字符串的最大长度为4个字符,最终生成的Swagger文件中该字段应包含如下配置:
"STRING_LIST" : { "type" : "array", "description" : "A list of strings", "items" : { "type" : "string", "minLength": 0, "maxLength": 50 } }
依赖信息
<dependency> <groupId>io.swagger</groupId> <artifactId>swagger-models</artifactId> <version>1.6.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
问题描述
实际生成的Swagger文件中缺失了数组项的长度限制配置:
"STRING_LIST" : { "type" : "array", "description" : "A list of strings", "items" : { "type" : "string" } }
问询内容
请问需要如何配置才能实现上述需求?Swagger是否不支持为集合类型的元素设置校验限制规则?
问题原因
Swagger规范本身完全支持数组元素的校验规则配置,你遇到的问题是当前使用的Springfox 2.9.2版本默认不支持解析Java 8及以上版本中泛型参数上的校验注解,不是Swagger本身的能力问题。
另外你示例中预期配置的maxLength:50和注解中写的@Size(max = 4)不一致,按实际需求调整注解参数即可。
解决方案
方案1:升级Springfox版本(推荐)
Springfox从3.0.0版本开始正式支持泛型参数上的JSR-380校验注解解析,直接替换依赖即可生效:
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency>
升级后原有代码无需修改,List<@Size(max = 4) String>的注解会被自动识别,生成的Swagger文件会自动在items字段下生成对应的minLength和maxLength配置。
方案2:不升级版本,兼容2.9.2
如果项目受依赖限制无法升级Springfox,可以通过扩展Springfox的ModelPropertyBuilderPlugin接口,手动实现泛型参数上的注解解析:
import org.springframework.stereotype.Component; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.schema.ModelPropertyBuilderPlugin; import springfox.documentation.spi.schema.contexts.ModelPropertyContext; import javax.validation.constraints.Size; import java.lang.reflect.AnnotatedType; import java.lang.reflect.ParameterizedType; @Component public class GenericValidationAnnotationPlugin implements ModelPropertyBuilderPlugin { @Override public void apply(ModelPropertyContext context) { context.getBeanPropertyDefinition() .map(def -> def.getField().getAnnotatedType()) .filter(type -> type instanceof ParameterizedType) .ifPresent(type -> { AnnotatedType[] typeArgs = ((ParameterizedType) type).getAnnotatedActualTypeArguments(); if (typeArgs.length > 0) { Size sizeAnnotation = typeArgs[0].getAnnotation(Size.class); if (sizeAnnotation != null) { context.getBuilder() .minLength(sizeAnnotation.min()) .maxLength(sizeAnnotation.max()); } } }); } @Override public boolean supports(DocumentationType delimiter) { return DocumentationType.SWAGGER_2.equals(delimiter); } }
添加该组件后,Springfox 2.9.2就可以自动识别泛型参数上的@Size注解,生成符合预期的Swagger配置。
内容的提问来源于stack exchange,提问作者CodeWizard1985
相关产品推荐
相关产品推荐

