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

如何配置Swagger使其不展示Spring Boot项目依赖的其他工程的API接口

解决方案

方案1:限定Swagger扫描的包路径(首选方案)

springfox默认会扫描Spring上下文中所有带@RestController、@RequestMapping注解的接口,不限定所属依赖包,你只需在项目A中自定义Swagger配置类,指定仅扫描项目A自身的根包即可:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.oas.annotations.EnableOpenApi;

@Configuration
@EnableOpenApi
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.OAS_30)
                .select()
                // 替换为你项目A的根包路径,例如com.yourcompany.projecta
                .apis(RequestHandlerSelectors.basePackage("com.yourcompany.projecta"))
                .paths(PathSelectors.any())
                .build();
    }
}

方案2:按接口路径过滤

如果依赖的B、C项目的接口有统一的路径前缀,也可以通过路径规则排除非项目A的接口,示例:

@Bean
public Docket api() {
    return new Docket(DocumentationType.OAS_30)
            .select()
            .apis(RequestHandlerSelectors.any())
            // 仅保留路径以/projecta/开头的接口,可根据你的实际路径规则调整
            .paths(PathSelectors.ant("/projecta/**"))
            .build();
}

方案3:排除依赖项目的Swagger配置

如果排查发现依赖的B、C项目自身包含Swagger的Docket配置,被Spring自动扫描加载导致多项目接口暴露,可以在项目A的启动类上添加扫描排除规则,过滤其他项目的配置类:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;

@SpringBootApplication
@ComponentScan(excludeFilters = {
        // 替换为B、C项目中Swagger配置类所在的包路径
        @ComponentScan.Filter(type = FilterType.REGEX, pattern = "com.yourcompany.projectb.config.*"),
        @ComponentScan.Filter(type = FilterType.REGEX, pattern = "com.yourcompany.projectc.config.*")
})
public class ProjectAApplication {
    public static void main(String[] args) {
        SpringApplication.run(ProjectAApplication.class, args);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 17:48:03