当前位置: 首页 > news >正文

SpringBoot2.7.14整合Swagger3.0的详细步骤及容易踩坑的地方

🧑‍💻作者名称:DaenCode
🎤作者简介:啥技术都喜欢捣鼓捣鼓,喜欢分享技术、经验、生活。
😎人生感悟:尝尽人生百味,方知世间冷暖。
📖所属专栏:SpringBoot实战


系列文章目录

以下是专栏部分内容,更多内容请前往专栏查看!

标题
一文带你学会使用SpringBoot+Avue实现短信通知功能(含重要文件代码)
一张思维导图带你学会Springboot创建全局异常、自定义异常
一张思维导图带你打通SpringBoot自定义拦截器的思路
28个SpringBoot项目中常用注解,日常开发、求职面试不再懵圈
一张思维导图带你学会SpringBoot、Vue前后端分离项目线上部署
一张流程图带你学会SpringBoot结合JWT实现登录功能
一张思维导图带你学会使用SpringBoot中的Schedule定时发送邮件
一张思维导图带你学会使用SpringBoot异步任务实现下单校验库存
一张思维导图带你学会SpringBoot使用AOP实现日志管理功能

在这里插入图片描述


专栏推荐

  • 专门为Redis入门打造的专栏,包含Redis基础知识、基础命令、五大数据类型实战场景、key删除策略、内存淘汰机制、持久化机制、哨兵模式、主从复制、分布式锁等等内容。链接>>>>>>>>>《Redis从头学》
  • 专门为RabbitMQ入门打造的专栏,持续更新中。。。。。。。。链接>>>>>>>《图解RabbitMQ》

文章目录

  • 系列文章目录
  • 专栏推荐
  • 🌟引入依赖
  • 🌟applicationproperties配置文件
  • 🌟配置类创建
  • 🌟常用注解
  • 🌟具体用法
    • @ApiModel+@ApiModelProperty
    • @Api+@ApiOperation+@ApiParam
    • @ApiResponses+@ApiResponse
    • 效果查看
  • 🌟写在最后

🌟引入依赖

<!--swagger ui接口文档依赖--><dependency><groupId>io.springfox</groupId><artifactId>springfox-boot-starter</artifactId></dependency>

🌟applicationproperties配置文件

Springfox MVC路径匹配是基于AntPathMatcher的,而Spring Boot 2.7.14基于PathPatternMatcher。可以查看WebMvcProperties类

在这里插入图片描述因此,修改mvc的匹配策略为ant_path_matcher。如果swagger与springboot匹配策略不一致则会有错误:

Failed to start bean ‘ documentationPluginsBootstrapper ‘ ; nested exception…

spring.mvc.pathmatch.matching-strategy=ant_path_matcher

🌟配置类创建

@Component
@Data
@EnableOpenApi
public class SwaggerConfiguration {/*** 用户端接口文档* @return*/@Beanpublic Docket webApiDoc(){return new Docket(DocumentationType.OAS_30).groupName("用户端接口文档").pathMapping("/")//定义是否开启swagger.enable(true).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("top.daencode"))//正则匹配请求路径,并分配至当前分组.paths(PathSelectors.ant("/api/**")).build()//新版swagger3.0配置.globalRequestParameters(getGlobalRequestParameters()).globalResponses(HttpMethod.GET, getGlobalResponseMessage()).globalResponses(HttpMethod.POST, getGlobalResponseMessage());}/*** 管理端接口文档* @return*/@Beanpublic Docket adminApiDoc(){return new Docket(DocumentationType.OAS_30).groupName("管理端接口文档").pathMapping("/")//定义是否开启swagger.enable(true).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("top.daencode"))//正则匹配请求路径,并分配至当前分组.paths(PathSelectors.ant("/api/**")).build().globalRequestParameters();}/*** 接口文档元数据信息* @return*/private ApiInfo apiInfo(){return new ApiInfoBuilder().title("xxx项目接口文档").description("接口文档").contact(new Contact("daencode","https:daencode.top","shoanjen@126.com")).version("v1.0").build();}/*** 生成全局通用请求参数* @return*/private List<RequestParameter> getGlobalRequestParameters() {List<RequestParameter> parameters = new ArrayList<>();parameters.add(new RequestParameterBuilder().name("token").description("登录令牌").in(ParameterType.HEADER).query(q -> q.model(m -> m.scalarModel(ScalarType.STRING))).required(false).build());
//        可以配置多个
//        parameters.add(new RequestParameterBuilder()
//                .name("version")
//                .description("版本号")
//                .required(true)
//                .in(ParameterType.HEADER)
//                .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
//                .required(false)
//                .build());return parameters;}/*** 生成通用的接口文档响应信息* @return*/private List<Response> getGlobalResponseMessage() {List<Response> responseList = new ArrayList<>();responseList.add(new ResponseBuilder().code("4xx").description("请求错误,根据code和msg检查").build());return responseList;}
}

注意

  • 使用@EnableOpenApi开启swagger3.0。
  • apis(RequestHandlerSelectors.basePackage(“top.daencode”)):注意修改此处生效的包名。
  • .paths(PathSelectors.ant(“/api/**”)):修改接口的通用路径。
  • parameters.add:生成全局通用配置参数,比如说用户登录的token。

🌟常用注解

注解描述
@Api用于描述整个API接口的信息,包括API的标题、描述等。
@ApiOperation用于描述单个接口的操作信息,包括接口的HTTP方法、路径、描述等。
@ApiParam用于描述接口参数的信息,包括参数名、类型、描述等。
@ApiModel用于描述接口返回结果或请求体的模型信息。
@ApiModelProperty用于描述模型属性的信息,包括属性名、类型、描述等。
@ApiIgnore用于忽略某个API接口,使其不在生成的文档中显示。
@ApiResponse用于描述接口的响应信息,包括响应码、描述、返回类型等。
@ApiResponses用于描述多个接口响应的信息,可以与@ApiResponse配合使用。

🌟具体用法

@ApiModel+@ApiModelProperty

@ApiModel("用户登录对象")
@Data
public class UserLogin {@ApiModelProperty(value = "用户名",example = "daencode")private String username;@ApiModelProperty(value = "密码",example = "123456")private String password;@ApiModelProperty(value = "验证码",example = "3425")private String captcha;
}

@Api+@ApiOperation+@ApiParam

@Api("用户模块")
@RestController
@RequestMapping("/api/v1/user")
public class UserController {@Autowiredprivate UserService userService;@PostMapping("login")@ApiOperation("用户登录")public JsonData login(@ApiParam("登录对象") @RequestBody UserLogin userLogin){//token为空则返回失败,否则返回成功String token=userService.login(userLogin);return token==null?JsonData.buildError("登录失败"):JsonData.buildSuccess(token);}
}

@ApiResponses+@ApiResponse

@ApiOperation("创建用户")
@ApiResponses(value = {@ApiResponse(code = 201, message = "用户创建成功", response = User.class),@ApiResponse(code = 400, message = "请求参数有误"),@ApiResponse(code = 401, message = "未授权访问"),@ApiResponse(code = 500, message = "服务器内部错误")
})
@PostMapping("/users")
public ResponseEntity<User> createUser(@RequestBody User user) {// ...
}

效果查看

1.前往postman发起接口请求测试。
在这里插入图片描述
2.访问:http://localhost:8080/swagger-ui/index.html,查看接口文档。
在这里插入图片描述


🌟写在最后

有关于SpringBoot2.7.14整合Swagger3.0的详细步骤及容易踩坑的地方到此就结束了。感谢大家的阅读,希望大家在评论区对此部分内容散发讨论,便于学到更多的知识。


请添加图片描述

http://www.lryc.cn/news/174785.html

相关文章:

  • 题解:ABC321D - Set Menu
  • 什么是Progressive Web App(PWA)?它们有哪些特点?
  • MySQL的高级SQL语句
  • 基于人脸5个关键点的人脸对齐(人脸纠正)
  • vue3中两个el-select下拉框选项相互影响
  • 博弈论——反应函数
  • UE5读取json文件
  • Vue中的插槽--组件复用,内容自定义
  • 完全指南:mv命令用法、示例和注意事项 | Linux文件移动与重命名
  • gitee生成公钥和远程仓库与本地仓库使用验证
  • 请求后端接口413
  • HarmonyOS之 开发环境搭建
  • QTC++ day12
  • Vue3中使用Proxy API取代defineProperty API的原因
  • 构建工具Webpack简介
  • Docker部署单点Elasticsearch与Kibana
  • opencv实现仿射变换和透射变换
  • 抖音seo账号矩阵源码系统
  • 性能优化之防抖
  • postgresql用户和角色
  • 设计模式之备忘录模式
  • 大数据Flink(八十八):Interval Join(时间区间 Join)
  • 数字IC笔试千题解--判断题篇(五)
  • Kubernetes(k8s)上搭建一主两从的mysql8集群
  • MySQL备份与恢复
  • 【RTOS学习】单片机中的C语言
  • 确知波束形成matlab仿真
  • 并发编程相关面试题
  • Cpp/Qt-day050921Qt
  • 视频汇聚/视频云存储/视频监控管理平台EasyCVR分发rtsp流起播慢优化步骤详解