Springdoc中类级别的@Schema(hidden=true)与@Hidden注解失效问题
我在开发Spring Boot项目时用Springdoc生成API文档,想要隐藏Swagger UI Schema里的特定类。尝试在类上添加OpenAPI 3的@Schema(hidden=true)和@Hidden注解,但完全没效果,类依然出现在Schema列表中。
类级别注解示例(无效)
@Getter @Setter @Entity @Hidden @Schema(hidden = true) @Table(name = "difficulty") @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) public class Difficulty { @Id @Column(name = "id", nullable = false) private Integer id; @Column(name = "name", nullable = false, length = 10) private String name; }

但在字段级别使用这些注解时却能正常生效,被标注的字段不会出现在Schema里:
字段级别注解示例(有效)
@Getter @Setter @Entity @Table(name = "difficulty") @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) public class Difficulty { @Id @Hidden @Column(name = "id", nullable = false) private Integer id; @Column(name = "name", nullable = false, length = 10) private String name; }

项目依赖配置:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.1.0</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>2.1.0</version> </dependency> <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-security</artifactId> <version>1.7.0</version> </dependency>
解决方案
1. 同步Springdoc依赖版本
你当前使用的springdoc-openapi-security版本1.7.0和springdoc-openapi-starter-webmvc-ui的2.1.0版本不兼容,Springdoc的核心starter包和附加模块版本必须保持一致,否则会出现注解失效等问题。
修改依赖版本为一致的2.1.0:
<dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-security</artifactId> <version>2.1.0</version> </dependency>
2. 自定义过滤器强制移除Schema(版本同步后仍无效时使用)
如果版本同步后类级别注解还是不生效,可以通过自定义OpenApiCustomiser手动移除指定类的Schema:
import io.swagger.v3.oas.models.OpenAPI; import org.springdoc.core.customizers.OpenApiCustomiser; import org.springframework.stereotype.Component; @Component public class HiddenSchemaFilter implements OpenApiCustomiser { @Override public void customise(OpenAPI openApi) { // 替换为你要隐藏的类的名称(对应Swagger Schema中显示的名称) openApi.getComponents().getSchemas().remove("Difficulty"); } }
3. 检查类的API引用情况
如果该类被Controller接口作为请求参数、返回值或泛型类型直接引用,Springdoc会自动将其加入Schema。这种情况下仅靠类级别注解无法隐藏,需要确保该类不在任何API接口签名中出现,或者配合上述过滤器强制移除。
内容的提问来源于stack exchange,提问作者Wikimmax
相关产品推荐
相关产品推荐

