Spring Boot项目Swagger UI页面无法访问的解决咨询
解决Spring Boot Swagger UI 404问题
1. 修正错误配置项
你application.properties里的springdoc.swagger-ui.url=/swagger-ui.html是错误配置,这个属性用于指定外部OpenAPI规范文件的路径,而非Swagger UI自身的访问路径。直接删除该配置即可,springdoc会自动处理默认路径映射。
修改后的application.properties:
server.port=8081
2. 确认依赖正确引入
你使用的是基于OpenAPI 3.0的springdoc-openapi,需根据Spring Boot版本引入对应starter依赖:
Maven(pom.xml)
- Spring Boot 3.x:
<dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>2.2.0</version> </dependency>
- Spring Boot 2.x:
<dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-ui</artifactId> <version>1.7.0</version> </dependency>
Gradle(build.gradle)
- Spring Boot 3.x:
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.2.0'
- Spring Boot 2.x:
implementation 'org.springdoc:springdoc-openapi-ui:1.7.0'
3. 使用正确的访问路径
不同版本的springdoc对应不同的默认访问路径:
- Spring Boot 2.x + springdoc v1.x:访问
http://localhost:8081/swagger-ui.html - Spring Boot 3.x + springdoc v2.x:默认访问
http://localhost:8081/swagger-ui/index.html,若需兼容旧路径,可添加以下配置到application.properties:
springdoc.swagger-ui.path=/swagger-ui.html
4. 排查拦截/安全配置(如有)
如果项目集成了Spring Security或自定义拦截器,需允许Swagger相关路径的访问,示例Spring Security配置:
@Configuration public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(auth -> auth .requestMatchers("/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html") .permitAll() .anyRequest() .authenticated() ); return http.build(); } }
5. 验证API规范生成状态
先访问http://localhost:8081/v3/api-docs,若能返回JSON格式的API规范,说明后端生成正常,问题仅在Swagger UI映射;若该路径也404,检查依赖是否正确、Controller是否被扫描到(你的Application类在org.example,Controller在org.example.Controller,包扫描逻辑正常)。
内容的提问来源于stack exchange,提问作者Burak Tanış
相关产品推荐
相关产品推荐

