Swagger快速上手教程以及一些运行报错解决

Swagger快速上手教程以及一些运行报错解决

一、swagger的介绍

官网:https://swagger.io/

1:Swagger作用简介

在现在,前后端分离的时代,前端人员写页面,后端人员提供接口,如果前后端人员无法做到“及早协商,尽早解决”,或者后端提供的接口,注释等不清楚,都会导致项目中问题的爆发。于是在这种大环境的背景下,Swagger孕育而生,①其号称世界上最流行的API框架;②采用可视化的RestFul风格,是一种API文档在线自动生成工具—>API文档与API定义同步更新;③支持在线测试功能

注:虽然Swagger有其在前后端交互中,有其众多优点,但是,请记住它只是用来做一些我们书写的接口代码的一些注释,有没有Swagger对我们的代码本身是没有影响的。

二、SpringBoot集成Swagger

1、创建SpringBoot项目,导入依赖:

 <!-- 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>

2、书写SwaggerConfig配置类

注:这些内容的格式大多是写死的,只需要修改一些字符串里面的内容即可

@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 fallback."

出现该问题的原因:
①:IDEA的目录结构出现问题,SpringApplication的启动类,应该在最外层,包含所有子包,不然启动时就会出现找不到启动类的情况,初学者很容易犯的错误!
![在这里插入图片描述](https://img-blog.csdnimg.cn/a43c157b84444863bbc7b8e6d7fcf0bf.png在这里插入图片描述

②:路径请求出现问题,找不到请求所对应的真实路径:
解决方法:实现 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());
    }
}

三、Swagger中常用的注解

1、@Api(tags = " **** ")
对我们的那个controller包名经行重命名或则注释,用于类上;
在这里插入图片描述

2、 @ApiOperation(value = " *** " ,notes = " *** ")
用于对我们写的接口进行说明,效果如下:
在这里插入图片描述
3、@PathVariable(value = " *** "): 指定参数的值
4、@ApiParam(" *** "):对参数经行解释
5、@ApiModel(" *** "):用于描述一个Modle的信息
6、@ApiModelProperty(" *** "):用于描述一个Modle的属性
作者一般用@ApiModel(" *** “)、@ApiModelProperty(” *** ")来描述,pojo实体类

四、案例展示:

1、准备工作

数据库与表的准备:
建一张orders表,表的内容如下:
在这里插入图片描述

Controller层:

@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);
    }

}

pojo层:

@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层:

@Mapper
@Repository
public interface Notice_orderMapper extends BaseMapper<Notice_order> {
     //增加一个订单通知内容
    int addNotice_order(Notice_order notice_order);
    //查询所有个订单通知内容
    List<Notice_order> queryAll();
}

Mapper.Xml

<?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.****.****.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 内容与上大致相同,就此省略,有需要的私信博主即可。。。。

2、访问Swagger界面

在完成上诉代码后,启动我们的SpringBoot程序,访问:http://localhost:8080/swagger-ui.html#/
效果如下:
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

3、如何进行接口的测试

点击 Try it out 经行测试,若接口带有参数,输入对应的参数值,即可测试接口。
![在这里插入图片描述](https://img-blog.csdnimg.cn/38183f5a26394aa0942a85fb249211f5.png在这里插入图片描述

总结

到这里博主觉得Swagger的功能与介绍已经差不多了,掌握这些对于Swagger来说应该是足够了,已经能帮助我们在项目中书写API文档了,如果有不足或者需要改进的地方,希望大家能指出,也希望能帮助到大家!

  • 15
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值