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

Spring Boot(Springfox)配置Swagger UI路径:移除/swagger-ui改为自定义路径

解决Springfox 3.0.0自定义Swagger UI访问路径(移除/swagger-ui)

你使用的是Springfox 3.0.0,之前配置无效的原因是:

  • springdoc.swagger-ui.path是SpringDoc OpenAPI的配置项,和Springfox不兼容;
  • springfox.documentation.swagger-ui.base-url仅用于给/swagger-ui添加前缀(比如设置为test后路径是/test/swagger-ui),无法替换整个路径。

以下两种方法可实现将Swagger UI访问路径改为localhost:8080/test:

方法一:控制器转发(简单快捷)

创建转发控制器,将/test路径重定向到Swagger UI默认页面:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class SwaggerRedirectController {

    @GetMapping("/test")
    public String redirectToSwagger() {
        return "redirect:/swagger-ui/index.html";
    }
}

访问localhost:8080/test时会自动跳转到Swagger UI页面,缺点是浏览器地址栏会显示/swagger-ui/index.html的路径。

方法二:重写Swagger UI资源映射(无跳转,路径保持/test)

通过自定义配置类修改Swagger UI的资源映射规则,让静态资源直接在/test路径下加载:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import springfox.documentation.swagger.web.UiConfiguration;
import springfox.documentation.swagger.web.UiConfigurationBuilder;
import springfox.documentation.swagger.web.UiConfigurationProperties;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import springfox.documentation.swagger.web.SwaggerUiWebMvcConfiguration;

@Configuration
public class CustomSwaggerUiConfig extends SwaggerUiWebMvcConfiguration {

    public CustomSwaggerUiConfig(SwaggerResourcesProvider swaggerResourcesProvider, UiConfigurationProperties uiConfiguration) {
        super(swaggerResourcesProvider, uiConfiguration);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 映射Swagger UI静态资源到/test路径
        registry.addResourceHandler("/test/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
        // 处理/test根路径指向index.html
        registry.addResourceHandler("/test")
                .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/index.html");
    }

    @Override
    protected UiConfiguration uiConfiguration() {
        // 设置Swagger UI内部资源的基准路径为/test
        return UiConfigurationBuilder.builder()
                .baseUrl("/test")
                .build();
    }
}

配置完成后,直接访问localhost:8080/test即可打开Swagger UI,浏览器地址栏保持/test路径,静态资源也能正确加载。

注意:请移除之前无效的配置项,避免冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 16:00:59