Springboot中集成swagger

Springboot中集成swagger

按照惯例,先上官网https://swagger.io/

什么是swagger

Swagger就是一个用来定义接口标准,接口规范,同时能根据你的代码自动生成接口说明文档的一个工具。费话不多说,代码往上堆

Springboot集成swagger2.x

swagger2.x时代我们选择2.9.2版本进行演示,我们使用现有的项目进行swagger集成演示

引入swagger2.9.2依赖

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

swagger配置类

/**
 * @Author: Christy
 * @Date: 2020/10/28 14:09
 * @DESC: Swagger2API文档的配置
 **/
@Configuration
@EnableSwagger2
public class Swagger2Config {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                // 指定构建api文档的详细信息的方法:apiInfo()
                .apiInfo(apiInfo())
                .select()
                // 指定要生成api接口的包路径,这里把controller作为包路径,生成controller中的所有接口
                .apis(RequestHandlerSelectors.basePackage("com.chinachg.tbsp.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                // 设置页面标题
                .title("银企直联管理系统")
                // 设置接口描述
                .description("银企直联管理系统API")
                // 设置联系方式
                .contact(new Contact("Christy", null, "bbxylqf@126.com"))
                // 设置版本
                .version("1.0")
                .build();
    }
}

启动应用

应用启动后,访问swagger-ui页面:http://localhost:8088/swagger-ui.html

在这里插入图片描述

我们点开test-controller中的第一个接口查看一下详细信息

在这里插入图片描述

我们点击右上角的Try it out可以在描述里面输入参数线测试我们接口

在这里插入图片描述

swagger2.x的使用

上面我们已经配置好了swagger2,并且也启动测试了一下,功能正常,下面我们开始使用swagger2。swagger2的使用主要是他的注解的使用,swagger2的注解可以分为两大类:controller(类)注解方法注解;方法注解又包括了修饰方法的注解修饰方法参数的注解以及修饰方法返回值的注解

@Api – Controller注解

顾名思义,该注解主要作用在类上,用来描述类或者接口的作用

/**
 * @Author Christy
 * @DESC
 * @Date 2020/11/12 9:56
 **/
@RestController
@RequestMapping("/test")
@Api(tags = "Springboot中参数传递的三个注解的使用")
public class TestController {
    
}

@ApiOperation – 方法注解

该注解主要是作用在方法上,用来说明该方法的作用,他有两个参数值得注意

value: 用来对接口的说明

notes:用来对接口的详细描述

/**
     * 
     * @author Christy
     * @date 2020/11/12 15:04
     * @param id
     * @param username
     * @return java.util.Map<java.lang.String,java.lang.Object>
     * @Desc ApiOperation中的notes支持html标签
     */
    @GetMapping("/testPathVariable01/{id}/{name}")
    @ApiOperation(value = "测试@PathVariable注解的第一种使用情况",
            notes = "<span style='color:red;'>描述:</span>&nbsp;用来测试@PathVariable注解的第一种使用情况")
    public Map<String, Object> testPathVariable01(@PathVariable Integer id, @PathVariable(value = "name") String username){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", id);
        jsonObject.put("username",username);
        return ResultInfo.getDataMap(jsonObject);
    }
@ApiImplicitParams – 参数注解

作用在方法上,用来对接口的中参数进行说明

/**
     *
     * @author Christy
     * @date 2020/11/12 15:04
     * @param id
     * @param username
     * @return java.util.Map<java.lang.String,java.lang.Object>
     * @Desc ApiOperation中的notes支持html标签
     */
    @GetMapping("/testPathVariable01/{id}/{name}")
    @ApiOperation(value = "测试@PathVariable注解的第一种使用情况",
            notes = "<span style='color:red;'>描述:</span>&nbsp;用来测试@PathVariable注解的第一种使用情况")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "用户id",dataType = "Integer",defaultValue = "1"),
            @ApiImplicitParam(name = "username",value = "用户姓名",dataType = "String",defaultValue = "christy")
    })
    public Map<String, Object> testPathVariable01(@PathVariable Integer id, @PathVariable(value = "name") String username){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", id);
        jsonObject.put("username",username);
        return ResultInfo.getDataMap(jsonObject);
    }
@ApiResponses – 返回值注解

作用在方法上,用来对接口的返回值进行说明,表示一组响应

/**
     *
     * @author Christy
     * @date 2020/11/12 15:04
     * @param id
     * @param username
     * @return java.util.Map<java.lang.String,java.lang.Object>
     * @Desc ApiOperation中的notes支持html标签
     */
    @GetMapping("/testPathVariable01/{id}/{name}")
    @ApiOperation(value = "测试@PathVariable注解的第一种使用情况",
            notes = "<span style='color:red;'>描述:</span>&nbsp;用来测试@PathVariable注解的第一种使用情况")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "用户id",dataType = "Integer",defaultValue = "1"),
            @ApiImplicitParam(name = "username",value = "用户姓名",dataType = "String",defaultValue = "christy")
    })
    @ApiResponses({
            @ApiResponse(code = 400, message = "参数错误"),
            @ApiResponse(code = 404, message = "请求路径不正确")
    })
    public Map<String, Object> testPathVariable01(@PathVariable Integer id, @PathVariable(value = "name") String username){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", id);
        jsonObject.put("username",username);
        return ResultInfo.getDataMap(jsonObject);
    }

以上注解配置完毕后,我们重新启动应用,查看效果

在这里插入图片描述

从上图可以看到我们之前配置的注解都已经生效了。

swagger2的3.x时代

上面项目中整合Swagger都是直接通过依赖springfox-swaggerspringfox-swagger-ui两个jar包来实现的,目前springfox 3.0.0版本已经有了自己的SpringBoot Starter,使用起来更契合SpringBoot项目,非常方便

我们把上面swagger2.x升级为3.x

引入官方3.x starter

<!--springfox swagger2.x时代-->
<!--<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>-->

<!--springfox swagger3.x时代我们使用官方Starter,记得将2.x的代码注释掉-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

swagger配置类

/**
 * @Author: Christy
 * @Date: 2020/10/28 14:09
 * @DESC: Swagger2API文档的配置,swagger2 3.x时代,注解@EnableSwagger2就不需要了
 **/
@Configuration
//@EnableSwagger2
public class Swagger2Config {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                // 指定构建api文档的详细信息的方法:apiInfo()
                .apiInfo(apiInfo())
                .select()
                // 指定要生成api接口的包路径,这里把controller作为包路径,生成controller中的所有接口
                .apis(RequestHandlerSelectors.basePackage("com.chinachg.tbsp.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                // 设置页面标题
                .title("银企直联管理系统")
                // 设置接口描述
                .description("银企直联管理系统API")
                // 设置联系方式
                .contact(new Contact("Christy", null, "bbxylqf@126.com"))
                // 设置版本
                .version("1.0")
                .build();
    }
}

启动项目

swagger-ui的访问路径在3.x发生了改变:http://localhost:8088/swagger-ui/

在这里插入图片描述

除了url,我们可以看到界面也稍微发生了些变化,其他的都一样。

swagger 3.X中的变化

那么对于swagger 3.x与2.x相比,发生了哪些变化呢

  • 旧版本需要依赖springfox-swagger2springfox-swagger-ui两个配置,新版本一个Starter就搞定了
  • 新版本去除了一些第三方依赖,包括guava,之前使用旧版本时就由于guava版本问题导致过依赖冲突
  • 新版本和旧版本文档访问路径发生了变化,新版本为:http://localhost:8088/swagger-ui/ ,旧版本为:http://localhost:8088/swagger-ui.html
  • 新版本中新增了一些SpringBoot配置,springfox.documentation.enabled配置可以控制是否启用Swagger文档生成功能。比如说我们只想在dev环境下启用Swagger文档,而在prod环境下不想启用,我们直接在SpringBoot配置文件中进行配置即可,springfox.documentation.enabledapplication-dev.yml配置为true,在application-prod.yml中配置为false

knife4j

简介

knife4j是springfox-swagger的增强UI实现,为Java开发者在使用Swagger的时候,提供了简洁、强大的接口文档体验。knife4j完全遵循了springfox-swagger中的使用方式,并在此基础上做了增强功能,如果你用过Swagger,你就可以无缝切换到knife4j

引入依赖

<!--整合Knife4j-->
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <version>3.0</version>
</dependency>

@EnableKnife4j注解

在Swagger2Config中增加一个@EnableKnife4j注解,该注解可以开启knife4j的增强功能

/**
 * @Author: Christy
 * @Date: 2020/10/28 14:09
 * @DESC: Swagger2API文档的配置
 **/
@Configuration
@EnableKnife4j
public class Swagger2Config {
    …………
}

启动应用

以前我们看接口文档都是访问swagger-ui的地址,现在我们集成了knife4j,直接访问他的文档接口地址就行了:http://localhost:8088/doc.html

在这里插入图片描述

这么看起来是不是瞬间觉得高大上很多了?我们打开上面我们配置的接口,看看界面

在这里插入图片描述

上面是接口的文档选项卡,下面还有调试open两个选项卡,我们依次打开看一下

在这里插入图片描述

调试选项卡可以供我们直接在线测试接口

在这里插入图片描述

open选项卡将我们的接口的详细信息,包括我们配置的swagger信息都详细的列举了出来,还能下载保存成json文件

而且在文档管理离线文档中还可以导出我们的接口文档,提供多种格式

在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潮汐先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值