You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringDoc生成API文档时如何移除多余控制器与Schema?

解决SpringDoc显示多余Controller和Schemas的方法

1. 移除自动生成的ProfileController

你引入的spring-boot-starter-data-rest会自动注册ProfileController,可以通过两种方式处理:

配置文件过滤

在application.properties或application.yml中添加配置:

# 只扫描你自己的控制器所在包
springdoc.packages-to-scan=com.app.controller

或者直接排除特定路径:

springdoc.paths-to-exclude=/profile/**

代码配置类

创建一个OpenAPI配置类,手动指定要展示的API范围:

import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OpenApiConfig {
    @Bean
    public GroupedOpenApi todoAppApi() {
        return GroupedOpenApi.builder()
                .group("todo-app-api")
                .packagesToScan("com.app.controller") // 替换为你实际的控制器包路径
                .pathsToMatch("/tasks/**", "/users/**") // 仅匹配你的业务API路径
                .build();
    }
}

2. 清理多余的Schemas

额外的Schemas大多是Spring Data REST或框架自带的类,可通过以下方式过滤:

配置文件方式

在application.properties中添加:

# 只包含你的实体类所在包
springdoc.schemas-to-scan=com.app.entity

或者直接排除框架相关包:

springdoc.packages-to-exclude=org.springframework.data.rest.webmvc,org.springframework.hateoas

代码配置类方式

在配置类中添加自定义处理器,精准保留需要的Schemas:

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Components;
import org.springdoc.core.customizers.OpenApiCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OpenApiConfig {
    @Bean
    public GroupedOpenApi todoAppApi() {
        return GroupedOpenApi.builder()
                .group("todo-app-api")
                .packagesToScan("com.app.controller")
                .pathsToMatch("/tasks/**", "/users/**")
                .addOpenApiCustomizer(removeUnwantedSchemas())
                .build();
    }

    private OpenApiCustomizer removeUnwantedSchemas() {
        return openApi -> {
            Components components = openApi.getComponents();
            if (components != null && components.getSchemas() != null) {
                // 仅保留Task和User实体的Schema
                components.getSchemas().keySet().removeIf(key -> 
                    !key.equals("Task") && !key.equals("User")
                );
            }
        };
    }
}

3. 优化依赖(可选)

你的项目基于Spring MVC(spring-boot-starter-web),但引入了webflux的UI依赖,完全可以删除该依赖以减少不必要的组件加载:

<!-- 移除多余的webflux依赖 -->
<!--<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webflux-ui</artifactId>
    <version>2.0.2</version>
</dependency>-->

内容的提问来源于stack exchange,提问作者Youssef Gamal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 18:07:16