如何在Springdoc Swagger UI中全局隐藏指定类型的所有属性?
全局屏蔽
@AssertTrue注解对应生成属性的实现方案 你可以通过自定义springdoc的全局定制器实现需求,不需要逐个属性配置hidden = true,以下是可直接落地的实现:
- 方案1:注册
OpenApiCustomiser全局过滤属性(推荐,侵入性最低)
直接在SpringDoc配置类中注册定制化Bean,在OpenAPI元数据生成完成后统一遍历所有Schema,移除所有标注了@AssertTrue注解(字段、方法级)对应的属性,代码如下:
import io.swagger.v3.oas.models.OpenAPI; import org.springdoc.core.customizers.OpenApiCustomiser; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.validation.constraints.AssertTrue; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Locale; import java.util.Map; @Configuration public class SpringDocGlobalConfig { @Bean public OpenApiCustomiser ignoreAssertTrueFieldCustomiser() { return openApi -> { // 遍历所有组件中注册的Schema模型 openApi.getComponents().getSchemas().forEach((schemaName, schema) -> { Map<String, io.swagger.v3.oas.models.media.Schema> properties = schema.getProperties(); if (properties == null || properties.isEmpty()) { return; } Class<?> targetClass = schema.getImplementation(); if (targetClass == null) { return; } // 移除字段上标注@AssertTrue生成的属性 for (Field field : targetClass.getDeclaredFields()) { if (field.isAnnotationPresent(AssertTrue.class)) { properties.remove(field.getName()); } } // 移除getter方法上标注@AssertTrue生成的属性 for (Method method : targetClass.getDeclaredMethods()) { if (!method.isAnnotationPresent(AssertTrue.class)) { continue; } String methodName = method.getName(); String fieldName = null; // 处理普通getter:getXxx -> xxx if (methodName.startsWith("get") && methodName.length() > 3) { fieldName = methodName.substring(3, 4).toLowerCase(Locale.ROOT) + methodName.substring(4); } // 处理布尔类型getter:isXxx -> xxx else if (methodName.startsWith("is") && methodName.length() > 2) { fieldName = methodName.substring(2, 3).toLowerCase(Locale.ROOT) + methodName.substring(3); } if (fieldName != null) { properties.remove(fieldName); } } }); }; } }
该配置全局生效,无论@AssertTrue标注在字段还是校验方法上,对应的属性都不会出现在最终生成的OpenAPI定义中,不需要改动任何业务代码。
注意:如果你的项目使用SpringBoot 3+/Jakarta EE 9+版本,需要将代码中导入的
javax.validation.constraints.AssertTrue替换为jakarta.validation.constraints.AssertTrue,其余逻辑无需调整。
- 方案2:自定义模型属性定制器(适合需要同时调整其他校验注解生成规则的场景)
如果需要同时修改其他JSR-380校验注解的Schema生成逻辑,可以实现PropertyCustomizer接口,注册为Spring Bean,在解析属性阶段遇到带@AssertTrue注解的属性时,直接设置属性为隐藏:
import org.springdoc.core.customizers.PropertyCustomizer; import org.springframework.stereotype.Component; import io.swagger.v3.oas.models.media.Schema; import java.lang.reflect.AnnotatedElement; import javax.validation.constraints.AssertTrue; @Component public class AssertTrueIgnoreCustomizer implements PropertyCustomizer { @Override public Schema customize(Schema property, AnnotatedElement annotatedElement) { if (annotatedElement.isAnnotationPresent(AssertTrue.class)) { property.setHidden(true); } return property; } }
注意这个方案只能处理字段、getter方法上直接标注注解生成的属性,如果是通过类级别校验逻辑生成的属性无法覆盖,优先选择方案1兼容性更好。
内容的提问来源于stack exchange,提问作者WedgeOfGeese
相关产品推荐
相关产品推荐

