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

使用路径正则表达式时Swagger UI不展示API,如何解决?

问题分析与解决方案

1. API无法通过正则路径识别的原因及修复

你的Swagger配置中,路径匹配使用的regex("/rest.*")存在匹配逻辑问题:Swagger的正则匹配是严格基于完整请求路径的,/rest.*仅会匹配/rest后直接跟任意字符的路径(比如/resttest),但你的Controller路径是/rest/pattern/get-all-pattern这类多级子路径,该正则无法覆盖。

修复方案:改用Spring风格的Ant路径匹配,替换路径选择器:

.paths(PathSelectors.ant("/rest/**"))

/rest/**会匹配所有以/rest开头的多级子路径,完美适配你的Controller路由规则。

另外,你的配置类上标注了@EnableAutoConfiguration,但主类MyProjectApplication的@SpringBootApplication已经包含该注解,重复配置可能导致Swagger扫描逻辑异常,建议移除配置类中的@EnableAutoConfiguration。

调整后的Swagger配置类核心代码:

@org.springframework.context.annotation.Configuration
@PropertySource(value = "classpath:application.properties")
public class Configuration implements WebMvcConfigurer {
    // ... 跨域配置不变

    @Bean
    public Docket productApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.my.project.controller"))
                .paths(PathSelectors.ant("/rest/**"))
                .build();
    }
}

2. 隐藏Swagger UI中的模型展示

你不需要通过路径选择器来隐藏模型,直接在Docket配置中添加模型忽略规则即可:

@Bean
public Docket productApi(){
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.my.project.controller"))
            .paths(PathSelectors.ant("/rest/**"))
            .build()
            // 忽略所有Object类型的模型(间接隐藏大部分返回模型)
            .ignoredParameterTypes(Object.class)
            // 或者精准忽略特定模型类
            .ignoredParameterTypes(BaseAjaxResponse.class, PatternDto.class)
            // 关闭默认响应模型展示
            .useDefaultResponseMessages(false);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 20:55:16