如何通过注解处理Null值——Springfox Swagger 2
如何通过注解处理Null值——Springfox Swagger 2
我之前也踩过这个坑!用Springfox Swagger 2的时候,想让beacon_user_id字段在API文档的示例里显示成真正的null(不带引号的那种),结果直接给@ApiModelProperty的example设成"null",出来的却是字符串形式的"null",完全不是想要的效果。
后来摸索出几个可行的方案,给你参考:
方案一:自定义插件处理特定字段的"null"示例
这个方法最精准,能针对性地把你标注了example = "null"的字段转换成真正的null值,不会影响其他字段。
首先写个Swagger的ModelProperty插件:
@Component public class NullExampleConverterPlugin implements ModelPropertyBuilderPlugin { @Override public boolean supports(DocumentationType documentationType) { // 只对Swagger 2生效 return DocumentationType.SWAGGER_2.equals(documentationType); } @Override public void apply(ModelPropertyContext context) { // 读取字段上的@ApiModelProperty注解 Optional<ApiModelProperty> annotation = context.getBeanProperty().getAnnotatedElement() .map(elem -> elem.getAnnotation(ApiModelProperty.class)); if (annotation.isPresent()) { String exampleValue = annotation.get().example(); // 如果注解里的example是"null",就把Swagger示例改成真正的null if ("null".equals(exampleValue)) { context.getBuilder().example(null); } } } @Override public void setOrder(int order) { // 确保这个插件在默认的ModelProperty插件之后执行 ModelPropertyBuilderPlugin.super.setOrder(Ordered.HIGHEST_PRECEDENCE + 1); } }
然后回到你的实体类,还是用原来的注解写法就行:
@ApiModelProperty(value = "The beacon user ID", example = "null") private String beacon_user_id;
启动项目后,Swagger UI里这个字段的示例就会变成"beacon_user_id": null,完美符合你的需求!
方案二:全局配置处理所有"null"示例
如果你的项目里有很多字段都需要这种处理,那可以直接在Swagger的Docket配置里加全局规则,不用每个字段单独搞:
@Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.your.project.package")) .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()) // 自定义Model构建逻辑,替换所有example为"null"的字段 .modelBuilder(modelBuilder -> modelBuilder.defaultModelingStrategy(new DefaultModelingStrategy() { @Override public Model build(ModelContext context) { Model model = super.build(context); // 遍历所有字段,把example是"null"的改成真正的null model.getProperties().forEach((fieldName, property) -> { if ("null".equals(property.getExample())) { property.setExample(null); } }); return model; } })); }
这样不管哪个实体类的字段,只要你给@ApiModelProperty设了example = "null",都会自动转换成不带引号的null示例。
方案三:依赖Swagger的默认推断(简单但不够灵活)
如果你的实体类里这个字段本身的默认值就是null,而且你不需要强制显示示例为null,也可以试试不设置example属性,同时确保Swagger配置没有忽略null值的字段。不过这种方法不太可靠,因为Swagger有时候会根据字段类型推断示例(比如字符串类型可能会显示空字符串),所以只适合对示例要求不那么严格的场景。
总之,我个人最推荐方案一,精准可控,不会影响其他字段的示例显示,踩过坑亲测有效!
内容来源于stack exchange
相关产品推荐
相关产品推荐

