swagger
官网:https://swagger.io/
使用Swagger
添加依赖
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
编写接口
@RestController public class HelloController { @RequestMapping("/hello") public String hello(){ return "hello , swagger"; } }
集成Swagger2
@Configuration @EnableSwagger2 //开启Swagger2 public class SwaggerConfig {
访问:http://localhost:8083/swagger-ui.html
配置Swagger的apiInfo信息
@Configuration @EnableSwagger2 //开启Swagger2 public class SwaggerConfig { //配置Swagger2的Docket实例,并交给Spring容器管理 @Bean public Docket getDocket(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()); } //配置Swagger信息 private ApiInfo apiInfo(){ //作者信息 Contact contact = new Contact("", "", ""); return new ApiInfo( "Api Documentation", "Api Documentation", "1.0", "urn:tos", contact, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList()); } }
Swagger配置扫描接口
格式:Docket.select().apis().paths.build()
return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo())
.select() //RequestHandlerSelectors 配置扫描接口方式 //basePackage 扫描指定包 //any 扫描全部 //none 不扫描 //withClassAnnotation 扫描指定注解的类 //withMethodAnnotation 扫描指定注解的方法 .apis(RequestHandlerSelectors.basePackage("com.marw.controller")) //根据配置过滤请求路径 .paths(PathSelectors.ant("/")) .build();
配置启动Swagger
Docket.enable(false):关闭Swagger
Docket.enable(true):开启Swagger
根据发布环境设置Swagger开启或关闭
spring.profiles.active="dev"多环境配置
public Docket getDocket(Environment environment){ //设置开启Swagger的环境 Profiles profiles=Profiles.of("dev","uat"); //判断当前环境是否符合设置的开启Swagger的条件 boolean b = environment.acceptsProfiles(profiles); return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() //RequestHandlerSelectors 配置扫描接口方式 //basePackage 扫描指定包 //any 扫描全部 //none 不扫描 //withClassAnnotation 扫描指定注解的类 //withMethodAnnotation 扫描指定注解的方法 .apis(RequestHandlerSelectors.basePackage("com.marw.controller")) //根据配置过滤请求路径 //.paths(PathSelectors.ant("/")) .build().enable(b); }
配置API分组
Docket().groupName("分组名")
多个分组
本质多个Docket对象
//配置Swagger2的Docket实例,并交给Spring容器管理 @Bean public Docket a(){ return new Docket(DocumentationType.SWAGGER_2).groupName("A"); } //配置Swagger2的Docket实例,并交给Spring容器管理 @Bean public Docket b(){ return new Docket(DocumentationType.SWAGGER_2).groupName("B"); }
Models
Swagger扫描Models只要接口中返回值存在就会被扫描到Swagger中
@GetMapping("/index") public User index(){ return new User(); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律