SpringBoot 1.5.12集成Swagger UI 2.9.2实现可空属性方案问询
嘿,刚好我对SpringBoot 1.5.12搭配Swagger 2.9.2的配置挺熟的,给你梳理几个可行的解决方案:
一、通过Swagger注解直接配置可空属性
这是最直接的方式,利用@ApiModelProperty的属性就能实现你的需求:
- 在实体类的
surname字段上添加注解,指定允许空值、示例值为null,同时确保字段没有必填校验注解(比如@NotNull) - 代码示例:
public class UserRequest { private Long id; private String name; @ApiModelProperty( value = "姓氏,支持字符串或null", allowEmptyValue = true, example = "null", dataType = "String" ) private String surname; // getter、setter方法省略 }
- 说明:
allowEmptyValue = true会让Swagger识别该字段允许空值(包括null),example = "null"会让请求体示例中显示surname: null,完全符合你要的效果。
二、通过swagger.yaml配置文件实现
如果你习惯用yaml定义API规范,也可以这么做:
- 注意:springfox 2.9.2主要支持Swagger 2.0规范,所以可空属性需要用扩展字段
x-nullable: true,OpenAPI 3.0的nullable: true在这个版本不生效 - yaml示例:
paths: /your-api-path: post: summary: 提交用户数据 requestBody: content: application/json: schema: type: object properties: id: type: integer name: type: string surname: type: string x-nullable: true example: null example: id: 2 name: 'test' surname: null
三、如果上述方法不生效,重写Swagger类的解决方案
偶尔会因为版本兼容性问题,注解或yaml的设置没生效,这时候可以通过自定义Swagger插件来强制修改字段属性:
- 自定义
ModelPropertyBuilderPlugin实现类,控制字段的可空性:
import springfox.documentation.builders.ModelPropertyBuilder; import springfox.documentation.schema.Annotations; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.schema.ModelPropertyBuilderPlugin; import springfox.documentation.spi.schema.contexts.ModelPropertyContext; import java.util.Optional; public class NullableFieldPlugin implements ModelPropertyBuilderPlugin { @Override public void apply(ModelPropertyContext context) { // 方式1:针对带有allowEmptyValue=true的@ApiModelProperty字段 Optional<ApiModelProperty> apiModelProperty = Annotations.findAnnotation( context.getBeanPropertyDefinition().getField(), ApiModelProperty.class ); if (apiModelProperty.isPresent() && apiModelProperty.get().allowEmptyValue()) { context.getBuilder().nullable(true).example("null"); } // 方式2:直接指定特定字段(比如surname) if ("surname".equals(context.getBeanPropertyDefinition().getField().getName())) { context.getBuilder().nullable(true).example("null"); } } @Override public boolean supports(DocumentationType documentationType) { return DocumentationType.SWAGGER_2.equals(documentationType); } }
- 在Swagger配置类中注册这个插件:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public NullableFieldPlugin nullableFieldPlugin() { return new NullableFieldPlugin(); } }
内容的提问来源于stack exchange,提问作者Fabry
相关产品推荐
相关产品推荐

