学习笔记 —— Swagger快速上手教程以及一些运行报错解决
Swagger快速上手教程以及一些运行报错解决
官网:https://swagger.io/
在现在,前后端分离的时代,前端人员写页面,后端人员提供接口,如果前后端人员无法做到“及早协商,尽早解决”,或者后端提供的接口,注释等不清楚,都会导致项目中问题的爆发。于是在这种大环境的背景下,Swagger孕育而生,①其号称世界上最流行的API框架;②采用可视化的RestFul风格,是一种API文档在线自动生成工具—>API文档与API定义同步更新;③支持在线测试功能。
注:虽然Swagger有其在前后端交互中,有其众多优点,但是,请记住它只是用来做一些我们书写的接口代码的一些注释,有没有Swagger对我们的代码本身是没有影响的。
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency>
注:这些内容的格式大多是写死的,只需要修改一些字符串里面的内容即可
@Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket docket(){ return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()) .groupName("gao") .select() .apis(RequestHandlerSelectors.basePackage("com.****.****.controller"))//绑定扫描的包 .build(); } private ApiInfo apiInfo(){//这些内容对应Swagger页面的一些内容,一一对应修改即可 Contact contact = new Contact("优秀的男人", "http:www.baidu.com", "3331416666@qq.com"); return new ApiInfo( "***项目API文档", "直挂云帆济沧海", "v1.0", "http:www.baidu.com", contact, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList()); } }
其运行对应的Swagger-UI界面如下:
如果不出意外的话,以上代码就可以,正常运行,使用Swagger了,但是还是会出现一些特殊的报错情况,博主结合自己的情况,做了一下的一些报错情况的解决,没有问题的友友,可以自动屏蔽。
3、Swagger的运行报错一:IDEA报错显示 “Failed to start bean ‘documentationPluginsBootstrapper’; nested exception is java.lang.NullPointerException”
出现该问题的原因:Springfox使用的路径匹配是基于AntPathMatcher的,而Spring Boot 2.6.X使用的是PathPatternMatcher。
解决方法:
①:在该配置类上添加注解:@EnableWebMvc 来改变匹配规则
②:在application.yaml或则application.properties文件中添加该语句:
spring.mvc.pathmatch.matching-strategy=ant_path_matcher 来改变匹配规则,注意yaml与properties文件的书写格式即可。
③:降低Swagger的版本 降低到 2.5.* 版本即可
4、Swagger的运行报错二:IDEA报错显示"This application has no explicit mapping for /error, so you are seeing this as a fallbac出现该问题的原因:
①:IDEA的目录结构出现问题,SpringApplication的启动类,应该在最外层,包含所有子包,不然启动时就会出现找不到启动类的情况,初学者很容易犯的错误!
②:路径请求出现问题,找不到请求所对应的真实路径:
解决方法:实现 WebMvcConfigurer 类,重写 addResourceHandlers 接口,在addResourceHandlers中addResourceHandler()添加的是访问路径,addResourceLocations()中添加的是映射后的真实路径。代码结构如下(是死的结构):
@EnableWebMvc @Configuration @EnableSwagger2 public class SwaggerConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**").addResourceLocations( "classpath:/static/"); registry.addResourceHandler("swagger-ui.html").addResourceLocations( "classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**").addResourceLocations( "classpath:/META-INF/resources/webjars/"); WebMvcConfigurer.super.addResourceHandlers(registry); } @Bean public Docket docket(){ return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()) .groupName("gao") .select() .apis(RequestHandlerSelectors.basePackage("com.****.****.controller"))//绑定扫描的包 .build(); } private ApiInfo apiInfo(){//这些内容对应Swagger页面的一些内容,一一对应修改即可 Contact contact = new Contact("优秀的男人", "http:www.baidu.com", "3331416666@qq.com"); return new ApiInfo( "***项目API文档", "直挂云帆济沧海", "v1.0", "http:www.baidu.com", contact, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList()); } }
1、@Api(tags = " **** "):
对我们的那个controller包名经行重命名或则注释,用于类上;
2、 @ApiOperation(value = " *** " ,notes = " *** "):
用于对我们写的接口进行说明,效果如下:
3、@PathVariable(value = " *** "): 指定参数的值
4、@ApiParam(" *** "):对参数经行解释
5、@ApiModel(" *** "):用于描述一个Modle的信息
6、@ApiModelProperty(" *** "):用于描述一个Modle的属性
作者一般用@ApiModel(" *** “)、@ApiModelProperty(” *** ")来描述,pojo实体类
数据库与表的准备:
在mysql数据库中建一张orders表,表的内容如下:
@Api(tags = "****管理模块") @RestController @RequestMapping("/notice") public class NoticeController { @Autowired private Notice_orderServiceImpl notice_orderService; public void setNotice_orderService(Notice_orderServiceImpl notice_orderService) { this.notice_orderService = notice_orderService; } @ApiOperation(value = "查询接口",notes = "查询所有****的记录") @GetMapping("/queryAll") public List<Notice_order> QueryAll(){ List<Notice_order> notice_orders = notice_orderService.queryAll(); return notice_orders; } @ApiOperation(value = "增加接口",notes = "增加一个订单通知的记录") @PostMapping("/add/{notice_tips}/{order_id}/{payment_method}") public String Add(@PathVariable(value = "notice_tips")@ApiParam(value = "输入订单提示") String notice_tips, @PathVariable(value = "order_id")@ApiParam(value = "输入订单编号") String order_id , @PathVariable(value = "payment_method")@ApiParam(value = "输入支付方式") String payment_method){ int i = notice_orderService.addNotice_order(new Notice_order(null, notice_tips, order_id, new Date(), payment_method, new Date())); return i>0?"yes":"no"; } @ApiOperation("notice_order实体类") @GetMapping(value = "/order") public Notice_order f_order(){ return new Notice_order(1); } }
@ApiModel("notice_order实体类") @Data public class Notice_order implements Serializable { /** * id */ @TableId @ApiModelProperty("id") private Long id; /** * 通知提示 */ @ApiModelProperty("通知提示") private String notice_tips; /** * 订单编号 */ @ApiModelProperty("订单编号") private String order_id; /** * 下单时间 */ @ApiModelProperty("下单时间") private Date order_time; /** * 支付方式 */ @ApiModelProperty("支付方式") private String payment_method; /** * 支付时间 */ @ApiModelProperty("支付时间") private Date payment_time; //省略set,get,toString方法 }
@Mapper @Repository public interface Notice_orderMapper extends BaseMapper<Notice_order> { //增加一个订单通知内容 int addNotice_order(Notice_order notice_order); //查询所有个订单通知内容 List<Notice_order> queryAll(); }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.scujcc.babybear.mapper.Notice_orderMapper"> <select id="queryAll" resultType="com.****.****.pojo.Notice_order"> select * from mybatis.notice_order </select> <insert id="addNotice_order" parameterType="com.****.****.pojo.Notice_order"> insert into mybatis.notice_order(notice_tips,order_id,order_time,payment_method,payment_time)values (#{notice_tips},#{order_id},#{order_time},#{payment_method},#{payment_time}) </insert> </mapper>
Service层下的Service与ServiceImpl 内容与上大致相同,就此省略,有需要的私信博主即可。。。。
在完成上诉代码后,启动我们的SpringBoot程序,访问:http://localhost:8080/swagger-ui.html#/
效果如下:
点击 Try it out 经行测试,若接口带有参数,输入对应的参数值,即可测试接口。
到这里博主觉得Swagger的功能与介绍已经差不多了,掌握这些对于Swagger来说应该是足够了,已经能帮助我们在项目中书写API文档了,如果有不足或者需要改进的地方,希望大家能指出,也希望能帮助到大家!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!