Springboot配置Swagger
在 Spring Boot 项目中配置 Swagger 详细的步骤和说明:
1. 添加依赖
首先,在 pom.xml
文件中添加 Swagger 的相关依赖。推荐使用 springfox-boot-starter
或者 springdoc-openapi-ui
。
使用 springfox-boot-starter
(较旧但稳定)
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
使用 springdoc-openapi-ui
(更现代、推荐)
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.2.0</version>
</dependency>
2. 配置 Swagger
如果使用 springdoc-openapi-ui
无需额外配置,SpringDoc 会自动扫描并生成 Swagger UI。只需启动应用后访问以下地址即可:
http://localhost:8080/swagger-ui.html
如果使用 springfox-boot-starter
需要手动配置 Swagger Bean。创建一个配置类,例如 SwaggerConfig.java
:
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;
@Configuration
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) // 替换为你的控制器包路径
.paths(PathSelectors.any())
.build();
}
}
3. 启用 Swagger UI
对于 springdoc-openapi-ui
默认情况下,Swagger UI 已启用,直接访问以下地址即可:
http://localhost:8080/swagger-ui.html
对于 springfox-boot-starter
确保 Maven 依赖正确加载,并访问以下地址:
http://localhost:8080/swagger-ui/index.html
4. 自定义 Swagger 文档(可选)
可以通过 Docket
配置类自定义文档信息,例如标题、描述、版本等:
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("API 文档")
.description("这是一个示例项目的 API 文档")
.version("1.0.0")
.license("Apache 2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
.build();
}
5. 排除某些接口或路径(可选)
可以通过 RequestHandlerSelectors
和 PathSelectors
进行筛选。例如,排除某些路径:
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
.paths(PathSelectors.regex("/.*")) // 包含所有路径
.paths(path -> !path.matches("/admin/.*")) // 排除 /admin 开头的路径
6. 注意事项
-
Spring Boot 版本兼容性
springfox
支持 Spring Boot 2.x,但对 Spring Boot 3.x 支持较差。- 如果使用 Spring Boot 3.x,建议使用
springdoc-openapi-ui
。
-
生产环境禁用 Swagger
在生产环境中,建议禁用 Swagger UI,避免暴露 API 文档。可以通过以下方式禁用:- 对于
springdoc-openapi-ui
:springdoc.api-docs.enabled=false springdoc.swagger-ui.enabled=false
- 对于
springfox
:
在配置类中通过条件判断禁用:@Profile("!prod") // 仅在非 prod 环境下启用
- 对于
完成以上步骤后,启动项目并访问 Swagger UI 地址,即可查看和测试你的 API 文档!
本文作者:Titonay
本文链接:https://www.cnblogs.com/Titonay/p/18730759
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步