SpringBoot集成Swagger以及常用注解

一、什么是Swagger

官方描述:

原文:

Simplify API development for users, teams, and enterprises with the Swagger open source and professional toolset. Find out how Swagger can help you design and document your APIs at scale.

百度翻译:

使用Stragger开源和专业工具集简化用户、团队和企业的API开发。了解Swagger如何帮助您大规模地设计和记录API。

个人理解:

Swagger说白了就是一个便于前后端开发人员管理、测试和使用API的工具,一般用于前后端分离模式,功能类似于Postman

一般流程为:后端人员开发接口并集成Swagger ——> 导出接口文档或直接告知前端人员swagger-ui的URL地址 ——> 前端人员根据接口文档或swagger-ui在线查看接口进行调用获取数据 ——> 后端根据前端需求实时更新接口信息 ——> 项目上线(重点在swagger的使用上,其他环节已经略过~)

Swagger的实时性对于前后端联调是十分友好的

(以上仅为个人理解,如有错误,请各位带佬批评指正!)

二、SpringBoot集成Swagger(Swagger版本2.9.2及以上)

首先请检查你的SpringBoot的版本信息(在pom.xml文件中):

在这里插入图片描述

有两种情况:版本在2.6.0(包含2.6.0)以上、版本在2.6.0以下

2.6.0以上:

在pom.xml中引入如下依赖():
		<!-- 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>
编辑resource/application.yml文件,添加如下配置:
spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

2.6.0以下:

只需导入依赖即可:
	<!-- 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>

三、Swagger常用注解:

//在Controller层的应用:
//1.在类上应用的注解:
@Api(tags = "这是一个控制器类")
//2.在具体请求方法上的注解:
@ApiOperation(value = "功能总述" , notes = "具体描述")
@ApiParam(value = "请求参数说明")

//在POJO层的应用:
//1.在类上应用的注解:
@ApiModel(description = "XX实体类")
//2.在实体类属性上应用的注解:
@ApiModelProperty(value = "属性说明")

四、访问Swagger-UI:

Swagger版本为2.9.2:

直接访问:localhost:8080/swagger-ui.html

Swagger版本为3.0.0:

直接访问:localhost:8080/swagger-ui/index.html

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐